blob: a2ea0dec3e9d0f99e5015ec22181a4b339745f14 [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"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000022#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000023#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/GlobalValue.h"
26#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000027#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000029#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000030
31using namespace clang;
32using namespace CodeGen;
33
Benjamin Kramerc52193f2014-10-10 13:57:57 +000034namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000035/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000036class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
37public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000038 /// \brief Kinds of OpenMP regions used in codegen.
39 enum CGOpenMPRegionKind {
40 /// \brief Region with outlined function for standalone 'parallel'
41 /// directive.
42 ParallelOutlinedRegion,
43 /// \brief Region with outlined function for standalone 'task' directive.
44 TaskOutlinedRegion,
45 /// \brief Region for constructs that do not require function outlining,
46 /// like 'for', 'sections', 'atomic' etc. directives.
47 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000048 /// \brief Region with outlined function for standalone 'target' directive.
49 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000050 };
Alexey Bataev18095712014-10-10 12:19:54 +000051
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 CGOpenMPRegionInfo(const CapturedStmt &CS,
53 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000054 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
55 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000056 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000057 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058
59 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000060 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
61 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000062 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000063 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064
65 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000066 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000067 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000068
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000069 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000070 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000071
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000072 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000073 /// \return LValue for thread id variable. This LValue always has type int32*.
74 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000075
Alexey Bataev48591dd2016-04-20 04:01:36 +000076 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
77
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000078 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079
Alexey Bataev81c7ea02015-07-03 09:56:58 +000080 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
81
Alexey Bataev25e5b442015-09-15 12:52:43 +000082 bool hasCancel() const { return HasCancel; }
83
Alexey Bataev18095712014-10-10 12:19:54 +000084 static bool classof(const CGCapturedStmtInfo *Info) {
85 return Info->getKind() == CR_OpenMP;
86 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000087
Alexey Bataev48591dd2016-04-20 04:01:36 +000088 ~CGOpenMPRegionInfo() override = default;
89
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000091 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000092 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000093 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000094 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000095};
Alexey Bataev18095712014-10-10 12:19:54 +000096
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000097/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000098class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000099public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000101 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000102 OpenMPDirectiveKind Kind, bool HasCancel,
103 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000104 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
105 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000107 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
108 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000109
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000110 /// \brief Get a variable or parameter for storing global thread id
111 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000112 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000113
Alexey Bataev18095712014-10-10 12:19:54 +0000114 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000116
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000117 static bool classof(const CGCapturedStmtInfo *Info) {
118 return CGOpenMPRegionInfo::classof(Info) &&
119 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
120 ParallelOutlinedRegion;
121 }
122
Alexey Bataev18095712014-10-10 12:19:54 +0000123private:
124 /// \brief A variable or parameter storing global thread id for OpenMP
125 /// constructs.
126 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000127 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000128};
129
Alexey Bataev62b63b12015-03-10 07:28:44 +0000130/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000131class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133 class UntiedTaskActionTy final : public PrePostActionTy {
134 bool Untied;
135 const VarDecl *PartIDVar;
136 const RegionCodeGenTy UntiedCodeGen;
137 llvm::SwitchInst *UntiedSwitch = nullptr;
138
139 public:
140 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
141 const RegionCodeGenTy &UntiedCodeGen)
142 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
143 void Enter(CodeGenFunction &CGF) override {
144 if (Untied) {
145 // Emit task switching point.
146 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
147 CGF.GetAddrOfLocalVar(PartIDVar),
148 PartIDVar->getType()->castAs<PointerType>());
149 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
150 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
151 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
152 CGF.EmitBlock(DoneBB);
153 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
154 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
155 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
156 CGF.Builder.GetInsertBlock());
157 emitUntiedSwitch(CGF);
158 }
159 }
160 void emitUntiedSwitch(CodeGenFunction &CGF) const {
161 if (Untied) {
162 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
163 CGF.GetAddrOfLocalVar(PartIDVar),
164 PartIDVar->getType()->castAs<PointerType>());
165 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
166 PartIdLVal);
167 UntiedCodeGen(CGF);
168 CodeGenFunction::JumpDest CurPoint =
169 CGF.getJumpDestInCurrentScope(".untied.next.");
170 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
171 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
172 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
173 CGF.Builder.GetInsertBlock());
174 CGF.EmitBranchThroughCleanup(CurPoint);
175 CGF.EmitBlock(CurPoint.getBlock());
176 }
177 }
178 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
179 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000180 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000181 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000182 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000183 OpenMPDirectiveKind Kind, bool HasCancel,
184 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000185 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000186 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000187 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
188 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000189
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190 /// \brief Get a variable or parameter for storing global thread id
191 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000193
194 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000195 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000196
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197 /// \brief Get the name of the capture helper.
198 StringRef getHelperName() const override { return ".omp_outlined."; }
199
Alexey Bataev48591dd2016-04-20 04:01:36 +0000200 void emitUntiedSwitch(CodeGenFunction &CGF) override {
201 Action.emitUntiedSwitch(CGF);
202 }
203
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000204 static bool classof(const CGCapturedStmtInfo *Info) {
205 return CGOpenMPRegionInfo::classof(Info) &&
206 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
207 TaskOutlinedRegion;
208 }
209
Alexey Bataev62b63b12015-03-10 07:28:44 +0000210private:
211 /// \brief A variable or parameter storing global thread id for OpenMP
212 /// constructs.
213 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000214 /// Action for emitting code for untied tasks.
215 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000216};
217
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000218/// \brief API for inlined captured statement code generation in OpenMP
219/// constructs.
220class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
221public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000222 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000223 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000224 OpenMPDirectiveKind Kind, bool HasCancel)
225 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
226 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000227 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000228
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000229 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000230 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000231 if (OuterRegionInfo)
232 return OuterRegionInfo->getContextValue();
233 llvm_unreachable("No context value for inlined OpenMP region");
234 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000235
Hans Wennborg7eb54642015-09-10 17:07:54 +0000236 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000237 if (OuterRegionInfo) {
238 OuterRegionInfo->setContextValue(V);
239 return;
240 }
241 llvm_unreachable("No context value for inlined OpenMP region");
242 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000243
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000244 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000245 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000246 if (OuterRegionInfo)
247 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000248 // If there is no outer outlined region,no need to lookup in a list of
249 // captured variables, we can use the original one.
250 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000251 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000252
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000253 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000254 if (OuterRegionInfo)
255 return OuterRegionInfo->getThisFieldDecl();
256 return nullptr;
257 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000258
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000259 /// \brief Get a variable or parameter for storing global thread id
260 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000261 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000262 if (OuterRegionInfo)
263 return OuterRegionInfo->getThreadIDVariable();
264 return nullptr;
265 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000266
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000267 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000268 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000269 if (auto *OuterRegionInfo = getOldCSI())
270 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000271 llvm_unreachable("No helper name for inlined OpenMP construct");
272 }
273
Alexey Bataev48591dd2016-04-20 04:01:36 +0000274 void emitUntiedSwitch(CodeGenFunction &CGF) override {
275 if (OuterRegionInfo)
276 OuterRegionInfo->emitUntiedSwitch(CGF);
277 }
278
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
280
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000281 static bool classof(const CGCapturedStmtInfo *Info) {
282 return CGOpenMPRegionInfo::classof(Info) &&
283 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
284 }
285
Alexey Bataev48591dd2016-04-20 04:01:36 +0000286 ~CGOpenMPInlinedRegionInfo() override = default;
287
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000288private:
289 /// \brief CodeGen info about outer OpenMP region.
290 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
291 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000292};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000293
Samuel Antaobed3c462015-10-02 16:14:20 +0000294/// \brief API for captured statement code generation in OpenMP target
295/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000296/// captured fields. The name of the target region has to be unique in a given
297/// application so it is provided by the client, because only the client has
298/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000299class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000300public:
301 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000302 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000303 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304 /*HasCancel=*/false),
305 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000306
307 /// \brief This is unused for target regions because each starts executing
308 /// with a single thread.
309 const VarDecl *getThreadIDVariable() const override { return nullptr; }
310
311 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000313
314 static bool classof(const CGCapturedStmtInfo *Info) {
315 return CGOpenMPRegionInfo::classof(Info) &&
316 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
317 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000318
319private:
320 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000321};
322
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000323static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000324 llvm_unreachable("No codegen for expressions");
325}
326/// \brief API for generation of expressions captured in a innermost OpenMP
327/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000328class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000329public:
330 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
331 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
332 OMPD_unknown,
333 /*HasCancel=*/false),
334 PrivScope(CGF) {
335 // Make sure the globals captured in the provided statement are local by
336 // using the privatization logic. We assume the same variable is not
337 // captured more than once.
338 for (auto &C : CS.captures()) {
339 if (!C.capturesVariable() && !C.capturesVariableByCopy())
340 continue;
341
342 const VarDecl *VD = C.getCapturedVar();
343 if (VD->isLocalVarDeclOrParm())
344 continue;
345
346 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
347 /*RefersToEnclosingVariableOrCapture=*/false,
348 VD->getType().getNonReferenceType(), VK_LValue,
349 SourceLocation());
350 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
351 return CGF.EmitLValue(&DRE).getAddress();
352 });
353 }
354 (void)PrivScope.Privatize();
355 }
356
357 /// \brief Lookup the captured field decl for a variable.
358 const FieldDecl *lookup(const VarDecl *VD) const override {
359 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
360 return FD;
361 return nullptr;
362 }
363
364 /// \brief Emit the captured statement body.
365 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
366 llvm_unreachable("No body for expressions");
367 }
368
369 /// \brief Get a variable or parameter for storing global thread id
370 /// inside OpenMP construct.
371 const VarDecl *getThreadIDVariable() const override {
372 llvm_unreachable("No thread id for expressions");
373 }
374
375 /// \brief Get the name of the capture helper.
376 StringRef getHelperName() const override {
377 llvm_unreachable("No helper name for expressions");
378 }
379
380 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
381
382private:
383 /// Private scope to capture global variables.
384 CodeGenFunction::OMPPrivateScope PrivScope;
385};
386
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000387/// \brief RAII for emitting code of OpenMP constructs.
388class InlinedOpenMPRegionRAII {
389 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000390 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
391 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000392
393public:
394 /// \brief Constructs region for combined constructs.
395 /// \param CodeGen Code generation sequence for combined directives. Includes
396 /// a list of functions used for code generation of implicitly inlined
397 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000398 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000399 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000400 : CGF(CGF) {
401 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000402 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
403 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000404 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
405 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
406 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000407 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000408
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 ~InlinedOpenMPRegionRAII() {
410 // Restore original CapturedStmtInfo only if we're done with code emission.
411 auto *OldCSI =
412 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
413 delete CGF.CapturedStmtInfo;
414 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000415 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
416 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000417 }
418};
419
Alexey Bataev50b3c952016-02-19 10:38:26 +0000420/// \brief Values for bit flags used in the ident_t to describe the fields.
421/// All enumeric elements are named and described in accordance with the code
422/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
423enum OpenMPLocationFlags {
424 /// \brief Use trampoline for internal microtask.
425 OMP_IDENT_IMD = 0x01,
426 /// \brief Use c-style ident structure.
427 OMP_IDENT_KMPC = 0x02,
428 /// \brief Atomic reduction option for kmpc_reduce.
429 OMP_ATOMIC_REDUCE = 0x10,
430 /// \brief Explicit 'barrier' directive.
431 OMP_IDENT_BARRIER_EXPL = 0x20,
432 /// \brief Implicit barrier in code.
433 OMP_IDENT_BARRIER_IMPL = 0x40,
434 /// \brief Implicit barrier in 'for' directive.
435 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
436 /// \brief Implicit barrier in 'sections' directive.
437 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
438 /// \brief Implicit barrier in 'single' directive.
439 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
440};
441
442/// \brief Describes ident structure that describes a source location.
443/// All descriptions are taken from
444/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
445/// Original structure:
446/// typedef struct ident {
447/// kmp_int32 reserved_1; /**< might be used in Fortran;
448/// see above */
449/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
450/// KMP_IDENT_KMPC identifies this union
451/// member */
452/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
453/// see above */
454///#if USE_ITT_BUILD
455/// /* but currently used for storing
456/// region-specific ITT */
457/// /* contextual information. */
458///#endif /* USE_ITT_BUILD */
459/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
460/// C++ */
461/// char const *psource; /**< String describing the source location.
462/// The string is composed of semi-colon separated
463// fields which describe the source file,
464/// the function and a pair of line numbers that
465/// delimit the construct.
466/// */
467/// } ident_t;
468enum IdentFieldIndex {
469 /// \brief might be used in Fortran
470 IdentField_Reserved_1,
471 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
472 IdentField_Flags,
473 /// \brief Not really used in Fortran any more
474 IdentField_Reserved_2,
475 /// \brief Source[4] in Fortran, do not use for C++
476 IdentField_Reserved_3,
477 /// \brief String describing the source location. The string is composed of
478 /// semi-colon separated fields which describe the source file, the function
479 /// and a pair of line numbers that delimit the construct.
480 IdentField_PSource
481};
482
483/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
484/// the enum sched_type in kmp.h).
485enum OpenMPSchedType {
486 /// \brief Lower bound for default (unordered) versions.
487 OMP_sch_lower = 32,
488 OMP_sch_static_chunked = 33,
489 OMP_sch_static = 34,
490 OMP_sch_dynamic_chunked = 35,
491 OMP_sch_guided_chunked = 36,
492 OMP_sch_runtime = 37,
493 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000494 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000495 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 /// \brief Lower bound for 'ordered' versions.
497 OMP_ord_lower = 64,
498 OMP_ord_static_chunked = 65,
499 OMP_ord_static = 66,
500 OMP_ord_dynamic_chunked = 67,
501 OMP_ord_guided_chunked = 68,
502 OMP_ord_runtime = 69,
503 OMP_ord_auto = 70,
504 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000505 /// \brief dist_schedule types
506 OMP_dist_sch_static_chunked = 91,
507 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000508 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
509 /// Set if the monotonic schedule modifier was present.
510 OMP_sch_modifier_monotonic = (1 << 29),
511 /// Set if the nonmonotonic schedule modifier was present.
512 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000513};
514
515enum OpenMPRTLFunction {
516 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
517 /// kmpc_micro microtask, ...);
518 OMPRTL__kmpc_fork_call,
519 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
520 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
521 OMPRTL__kmpc_threadprivate_cached,
522 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
523 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
524 OMPRTL__kmpc_threadprivate_register,
525 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
526 OMPRTL__kmpc_global_thread_num,
527 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
528 // kmp_critical_name *crit);
529 OMPRTL__kmpc_critical,
530 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
531 // global_tid, kmp_critical_name *crit, uintptr_t hint);
532 OMPRTL__kmpc_critical_with_hint,
533 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
534 // kmp_critical_name *crit);
535 OMPRTL__kmpc_end_critical,
536 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
537 // global_tid);
538 OMPRTL__kmpc_cancel_barrier,
539 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
540 OMPRTL__kmpc_barrier,
541 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
542 OMPRTL__kmpc_for_static_fini,
543 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
544 // global_tid);
545 OMPRTL__kmpc_serialized_parallel,
546 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
547 // global_tid);
548 OMPRTL__kmpc_end_serialized_parallel,
549 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
550 // kmp_int32 num_threads);
551 OMPRTL__kmpc_push_num_threads,
552 // Call to void __kmpc_flush(ident_t *loc);
553 OMPRTL__kmpc_flush,
554 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
555 OMPRTL__kmpc_master,
556 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
557 OMPRTL__kmpc_end_master,
558 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
559 // int end_part);
560 OMPRTL__kmpc_omp_taskyield,
561 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
562 OMPRTL__kmpc_single,
563 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
564 OMPRTL__kmpc_end_single,
565 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
566 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
567 // kmp_routine_entry_t *task_entry);
568 OMPRTL__kmpc_omp_task_alloc,
569 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
570 // new_task);
571 OMPRTL__kmpc_omp_task,
572 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
573 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
574 // kmp_int32 didit);
575 OMPRTL__kmpc_copyprivate,
576 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
577 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
578 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
579 OMPRTL__kmpc_reduce,
580 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
581 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
582 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
583 // *lck);
584 OMPRTL__kmpc_reduce_nowait,
585 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
586 // kmp_critical_name *lck);
587 OMPRTL__kmpc_end_reduce,
588 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
589 // kmp_critical_name *lck);
590 OMPRTL__kmpc_end_reduce_nowait,
591 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
592 // kmp_task_t * new_task);
593 OMPRTL__kmpc_omp_task_begin_if0,
594 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
595 // kmp_task_t * new_task);
596 OMPRTL__kmpc_omp_task_complete_if0,
597 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
598 OMPRTL__kmpc_ordered,
599 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
600 OMPRTL__kmpc_end_ordered,
601 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
602 // global_tid);
603 OMPRTL__kmpc_omp_taskwait,
604 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
605 OMPRTL__kmpc_taskgroup,
606 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
607 OMPRTL__kmpc_end_taskgroup,
608 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
609 // int proc_bind);
610 OMPRTL__kmpc_push_proc_bind,
611 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
612 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
613 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
614 OMPRTL__kmpc_omp_task_with_deps,
615 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
616 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
617 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
618 OMPRTL__kmpc_omp_wait_deps,
619 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
620 // global_tid, kmp_int32 cncl_kind);
621 OMPRTL__kmpc_cancellationpoint,
622 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
623 // kmp_int32 cncl_kind);
624 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000625 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
626 // kmp_int32 num_teams, kmp_int32 thread_limit);
627 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000628 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
629 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000630 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000631 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
632 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
633 // sched, kmp_uint64 grainsize, void *task_dup);
634 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000635 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
636 // num_dims, struct kmp_dim *dims);
637 OMPRTL__kmpc_doacross_init,
638 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
639 OMPRTL__kmpc_doacross_fini,
640 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
641 // *vec);
642 OMPRTL__kmpc_doacross_post,
643 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
644 // *vec);
645 OMPRTL__kmpc_doacross_wait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000646
647 //
648 // Offloading related calls
649 //
650 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
651 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
652 // *arg_types);
653 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000654 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
655 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
656 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
657 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000658 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
659 OMPRTL__tgt_register_lib,
660 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
661 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000662 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
663 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
664 OMPRTL__tgt_target_data_begin,
665 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
666 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
667 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000668 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
669 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
670 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000671};
672
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000673/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
674/// region.
675class CleanupTy final : public EHScopeStack::Cleanup {
676 PrePostActionTy *Action;
677
678public:
679 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
680 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
681 if (!CGF.HaveInsertPoint())
682 return;
683 Action->Exit(CGF);
684 }
685};
686
Hans Wennborg7eb54642015-09-10 17:07:54 +0000687} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000688
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000689void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
690 CodeGenFunction::RunCleanupsScope Scope(CGF);
691 if (PrePostAction) {
692 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
693 Callback(CodeGen, CGF, *PrePostAction);
694 } else {
695 PrePostActionTy Action;
696 Callback(CodeGen, CGF, Action);
697 }
698}
699
Alexey Bataev18095712014-10-10 12:19:54 +0000700LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000701 return CGF.EmitLoadOfPointerLValue(
702 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
703 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000704}
705
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000706void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000707 if (!CGF.HaveInsertPoint())
708 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000709 // 1.2.2 OpenMP Language Terminology
710 // Structured block - An executable statement with a single entry at the
711 // top and a single exit at the bottom.
712 // The point of exit cannot be a branch out of the structured block.
713 // longjmp() and throw() must not violate the entry/exit criteria.
714 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000715 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000716 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000717}
718
Alexey Bataev62b63b12015-03-10 07:28:44 +0000719LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
720 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000721 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
722 getThreadIDVariable()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000723 LValueBaseInfo(AlignmentSource::Decl, false));
Alexey Bataev62b63b12015-03-10 07:28:44 +0000724}
725
Alexey Bataev9959db52014-05-06 10:08:46 +0000726CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000727 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000728 IdentTy = llvm::StructType::create(
729 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
730 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +0000731 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000732 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000733
734 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000735}
736
Alexey Bataev91797552015-03-18 04:13:55 +0000737void CGOpenMPRuntime::clear() {
738 InternalVars.clear();
739}
740
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000741static llvm::Function *
742emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
743 const Expr *CombinerInitializer, const VarDecl *In,
744 const VarDecl *Out, bool IsCombiner) {
745 // void .omp_combiner.(Ty *in, Ty *out);
746 auto &C = CGM.getContext();
747 QualType PtrTy = C.getPointerType(Ty).withRestrict();
748 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000749 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +0000750 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000751 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +0000752 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000753 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000754 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000755 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000756 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000757 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
758 auto *Fn = llvm::Function::Create(
759 FnTy, llvm::GlobalValue::InternalLinkage,
760 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
761 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000762 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000763 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000764 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000765 CodeGenFunction CGF(CGM);
766 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
767 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
768 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
769 CodeGenFunction::OMPPrivateScope Scope(CGF);
770 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
771 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
772 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
773 .getAddress();
774 });
775 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
776 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
777 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
778 .getAddress();
779 });
780 (void)Scope.Privatize();
781 CGF.EmitIgnoredExpr(CombinerInitializer);
782 Scope.ForceCleanup();
783 CGF.FinishFunction();
784 return Fn;
785}
786
787void CGOpenMPRuntime::emitUserDefinedReduction(
788 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
789 if (UDRMap.count(D) > 0)
790 return;
791 auto &C = CGM.getContext();
792 if (!In || !Out) {
793 In = &C.Idents.get("omp_in");
794 Out = &C.Idents.get("omp_out");
795 }
796 llvm::Function *Combiner = emitCombinerOrInitializer(
797 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
798 cast<VarDecl>(D->lookup(Out).front()),
799 /*IsCombiner=*/true);
800 llvm::Function *Initializer = nullptr;
801 if (auto *Init = D->getInitializer()) {
802 if (!Priv || !Orig) {
803 Priv = &C.Idents.get("omp_priv");
804 Orig = &C.Idents.get("omp_orig");
805 }
806 Initializer = emitCombinerOrInitializer(
807 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
808 cast<VarDecl>(D->lookup(Priv).front()),
809 /*IsCombiner=*/false);
810 }
811 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
812 if (CGF) {
813 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
814 Decls.second.push_back(D);
815 }
816}
817
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000818std::pair<llvm::Function *, llvm::Function *>
819CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
820 auto I = UDRMap.find(D);
821 if (I != UDRMap.end())
822 return I->second;
823 emitUserDefinedReduction(/*CGF=*/nullptr, D);
824 return UDRMap.lookup(D);
825}
826
John McCall7f416cc2015-09-08 08:05:57 +0000827// Layout information for ident_t.
828static CharUnits getIdentAlign(CodeGenModule &CGM) {
829 return CGM.getPointerAlign();
830}
831static CharUnits getIdentSize(CodeGenModule &CGM) {
832 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
833 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
834}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000835static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000836 // All the fields except the last are i32, so this works beautifully.
837 return unsigned(Field) * CharUnits::fromQuantity(4);
838}
839static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000840 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000841 const llvm::Twine &Name = "") {
842 auto Offset = getOffsetOfIdentField(Field);
843 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
844}
845
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000846static llvm::Value *emitParallelOrTeamsOutlinedFunction(
847 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
848 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
849 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000850 assert(ThreadIDVar->getType()->isPointerType() &&
851 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000852 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000853 bool HasCancel = false;
854 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
855 HasCancel = OPD->hasCancel();
856 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
857 HasCancel = OPSD->hasCancel();
858 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
859 HasCancel = OPFD->hasCancel();
860 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000861 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +0000862 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000863 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000864}
865
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000866llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
867 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
868 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
869 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
870 return emitParallelOrTeamsOutlinedFunction(
871 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
872}
873
874llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
875 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
876 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
877 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
878 return emitParallelOrTeamsOutlinedFunction(
879 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
880}
881
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000882llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
883 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000884 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
885 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
886 bool Tied, unsigned &NumberOfParts) {
887 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
888 PrePostActionTy &) {
889 auto *ThreadID = getThreadID(CGF, D.getLocStart());
890 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
891 llvm::Value *TaskArgs[] = {
892 UpLoc, ThreadID,
893 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
894 TaskTVar->getType()->castAs<PointerType>())
895 .getPointer()};
896 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
897 };
898 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
899 UntiedCodeGen);
900 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000901 assert(!ThreadIDVar->getType()->isPointerType() &&
902 "thread id variable must be of type kmp_int32 for tasks");
903 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000904 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000905 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000906 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
907 InnermostKind,
908 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000909 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000910 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
911 if (!Tied)
912 NumberOfParts = Action.getNumberOfParts();
913 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000914}
915
Alexey Bataev50b3c952016-02-19 10:38:26 +0000916Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000917 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000918 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000919 if (!Entry) {
920 if (!DefaultOpenMPPSource) {
921 // Initialize default location for psource field of ident_t structure of
922 // all ident_t objects. Format is ";file;function;line;column;;".
923 // Taken from
924 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
925 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000926 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000927 DefaultOpenMPPSource =
928 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
929 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000930
John McCall23c9dc62016-11-28 22:18:27 +0000931 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000932 auto fields = builder.beginStruct(IdentTy);
933 fields.addInt(CGM.Int32Ty, 0);
934 fields.addInt(CGM.Int32Ty, Flags);
935 fields.addInt(CGM.Int32Ty, 0);
936 fields.addInt(CGM.Int32Ty, 0);
937 fields.add(DefaultOpenMPPSource);
938 auto DefaultOpenMPLocation =
939 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
940 llvm::GlobalValue::PrivateLinkage);
941 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
942
John McCall7f416cc2015-09-08 08:05:57 +0000943 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000944 }
John McCall7f416cc2015-09-08 08:05:57 +0000945 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000946}
947
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000948llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
949 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000950 unsigned Flags) {
951 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000952 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000953 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000954 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000955 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000956
957 assert(CGF.CurFn && "No function in current CodeGenFunction.");
958
John McCall7f416cc2015-09-08 08:05:57 +0000959 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000960 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
961 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000962 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
963
Alexander Musmanc6388682014-12-15 07:07:06 +0000964 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
965 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000966 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000967 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000968 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
969 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000970 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000971 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000972 LocValue = AI;
973
974 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
975 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000976 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000977 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000978 }
979
980 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000981 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000982
Alexey Bataevf002aca2014-05-30 05:48:40 +0000983 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
984 if (OMPDebugLoc == nullptr) {
985 SmallString<128> Buffer2;
986 llvm::raw_svector_ostream OS2(Buffer2);
987 // Build debug location
988 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
989 OS2 << ";" << PLoc.getFilename() << ";";
990 if (const FunctionDecl *FD =
991 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
992 OS2 << FD->getQualifiedNameAsString();
993 }
994 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
995 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
996 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000997 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000998 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000999 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1000
John McCall7f416cc2015-09-08 08:05:57 +00001001 // Our callers always pass this to a runtime function, so for
1002 // convenience, go ahead and return a naked pointer.
1003 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001004}
1005
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001006llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1007 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001008 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1009
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001010 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001011 // Check whether we've already cached a load of the thread id in this
1012 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001013 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001014 if (I != OpenMPLocThreadIDMap.end()) {
1015 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001016 if (ThreadID != nullptr)
1017 return ThreadID;
1018 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001019 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001020 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001021 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001022 // Check if this an outlined function with thread id passed as argument.
1023 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001024 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1025 // If value loaded in entry block, cache it and use it everywhere in
1026 // function.
1027 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1028 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1029 Elem.second.ThreadID = ThreadID;
1030 }
1031 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001032 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001033 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001034
1035 // This is not an outlined function region - need to call __kmpc_int32
1036 // kmpc_global_thread_num(ident_t *loc).
1037 // Generate thread id value and cache this value for use across the
1038 // function.
1039 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1040 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1041 ThreadID =
1042 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1043 emitUpdateLocation(CGF, Loc));
1044 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1045 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001046 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001047}
1048
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001049void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001050 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001051 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1052 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001053 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1054 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1055 UDRMap.erase(D);
1056 }
1057 FunctionUDRMap.erase(CGF.CurFn);
1058 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001059}
1060
1061llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001062 if (!IdentTy) {
1063 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001064 return llvm::PointerType::getUnqual(IdentTy);
1065}
1066
1067llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001068 if (!Kmpc_MicroTy) {
1069 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1070 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1071 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1072 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1073 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001074 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1075}
1076
1077llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001078CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001079 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001080 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001081 case OMPRTL__kmpc_fork_call: {
1082 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1083 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001084 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1085 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001086 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001087 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001088 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1089 break;
1090 }
1091 case OMPRTL__kmpc_global_thread_num: {
1092 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001093 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001094 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001095 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001096 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1097 break;
1098 }
Alexey Bataev97720002014-11-11 04:05:39 +00001099 case OMPRTL__kmpc_threadprivate_cached: {
1100 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1101 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1102 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1103 CGM.VoidPtrTy, CGM.SizeTy,
1104 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1105 llvm::FunctionType *FnTy =
1106 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1107 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1108 break;
1109 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001110 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001111 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1112 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001113 llvm::Type *TypeParams[] = {
1114 getIdentTyPointerTy(), CGM.Int32Ty,
1115 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1116 llvm::FunctionType *FnTy =
1117 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1118 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1119 break;
1120 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001121 case OMPRTL__kmpc_critical_with_hint: {
1122 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1123 // kmp_critical_name *crit, uintptr_t hint);
1124 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1125 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1126 CGM.IntPtrTy};
1127 llvm::FunctionType *FnTy =
1128 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1129 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1130 break;
1131 }
Alexey Bataev97720002014-11-11 04:05:39 +00001132 case OMPRTL__kmpc_threadprivate_register: {
1133 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1134 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1135 // typedef void *(*kmpc_ctor)(void *);
1136 auto KmpcCtorTy =
1137 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1138 /*isVarArg*/ false)->getPointerTo();
1139 // typedef void *(*kmpc_cctor)(void *, void *);
1140 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1141 auto KmpcCopyCtorTy =
1142 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1143 /*isVarArg*/ false)->getPointerTo();
1144 // typedef void (*kmpc_dtor)(void *);
1145 auto KmpcDtorTy =
1146 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1147 ->getPointerTo();
1148 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1149 KmpcCopyCtorTy, KmpcDtorTy};
1150 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1151 /*isVarArg*/ false);
1152 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1153 break;
1154 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001155 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001156 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1157 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001158 llvm::Type *TypeParams[] = {
1159 getIdentTyPointerTy(), CGM.Int32Ty,
1160 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1161 llvm::FunctionType *FnTy =
1162 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1163 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1164 break;
1165 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001166 case OMPRTL__kmpc_cancel_barrier: {
1167 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1168 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001169 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1170 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001171 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1172 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001173 break;
1174 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001175 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001176 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001177 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1178 llvm::FunctionType *FnTy =
1179 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1180 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1181 break;
1182 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001183 case OMPRTL__kmpc_for_static_fini: {
1184 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1185 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1186 llvm::FunctionType *FnTy =
1187 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1188 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1189 break;
1190 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001191 case OMPRTL__kmpc_push_num_threads: {
1192 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1193 // kmp_int32 num_threads)
1194 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1195 CGM.Int32Ty};
1196 llvm::FunctionType *FnTy =
1197 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1198 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1199 break;
1200 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001201 case OMPRTL__kmpc_serialized_parallel: {
1202 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1203 // global_tid);
1204 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1205 llvm::FunctionType *FnTy =
1206 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1207 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1208 break;
1209 }
1210 case OMPRTL__kmpc_end_serialized_parallel: {
1211 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1212 // global_tid);
1213 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1214 llvm::FunctionType *FnTy =
1215 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1216 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1217 break;
1218 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001219 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001220 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001221 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1222 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001223 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001224 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1225 break;
1226 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001227 case OMPRTL__kmpc_master: {
1228 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1229 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1230 llvm::FunctionType *FnTy =
1231 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1232 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1233 break;
1234 }
1235 case OMPRTL__kmpc_end_master: {
1236 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1237 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1238 llvm::FunctionType *FnTy =
1239 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1240 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1241 break;
1242 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001243 case OMPRTL__kmpc_omp_taskyield: {
1244 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1245 // int end_part);
1246 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1247 llvm::FunctionType *FnTy =
1248 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1249 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1250 break;
1251 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001252 case OMPRTL__kmpc_single: {
1253 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1254 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1255 llvm::FunctionType *FnTy =
1256 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1257 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1258 break;
1259 }
1260 case OMPRTL__kmpc_end_single: {
1261 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1262 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1263 llvm::FunctionType *FnTy =
1264 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1265 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1266 break;
1267 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001268 case OMPRTL__kmpc_omp_task_alloc: {
1269 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1270 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1271 // kmp_routine_entry_t *task_entry);
1272 assert(KmpRoutineEntryPtrTy != nullptr &&
1273 "Type kmp_routine_entry_t must be created.");
1274 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1275 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1276 // Return void * and then cast to particular kmp_task_t type.
1277 llvm::FunctionType *FnTy =
1278 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1279 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1280 break;
1281 }
1282 case OMPRTL__kmpc_omp_task: {
1283 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1284 // *new_task);
1285 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1286 CGM.VoidPtrTy};
1287 llvm::FunctionType *FnTy =
1288 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1289 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1290 break;
1291 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001292 case OMPRTL__kmpc_copyprivate: {
1293 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001294 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001295 // kmp_int32 didit);
1296 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1297 auto *CpyFnTy =
1298 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001299 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001300 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1301 CGM.Int32Ty};
1302 llvm::FunctionType *FnTy =
1303 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1304 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1305 break;
1306 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001307 case OMPRTL__kmpc_reduce: {
1308 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1309 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1310 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1311 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1312 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1313 /*isVarArg=*/false);
1314 llvm::Type *TypeParams[] = {
1315 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1316 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1317 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1318 llvm::FunctionType *FnTy =
1319 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1320 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1321 break;
1322 }
1323 case OMPRTL__kmpc_reduce_nowait: {
1324 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1325 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1326 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1327 // *lck);
1328 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1329 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1330 /*isVarArg=*/false);
1331 llvm::Type *TypeParams[] = {
1332 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1333 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1334 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1335 llvm::FunctionType *FnTy =
1336 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1337 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1338 break;
1339 }
1340 case OMPRTL__kmpc_end_reduce: {
1341 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1342 // kmp_critical_name *lck);
1343 llvm::Type *TypeParams[] = {
1344 getIdentTyPointerTy(), CGM.Int32Ty,
1345 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1346 llvm::FunctionType *FnTy =
1347 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1348 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1349 break;
1350 }
1351 case OMPRTL__kmpc_end_reduce_nowait: {
1352 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1353 // kmp_critical_name *lck);
1354 llvm::Type *TypeParams[] = {
1355 getIdentTyPointerTy(), CGM.Int32Ty,
1356 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1357 llvm::FunctionType *FnTy =
1358 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1359 RTLFn =
1360 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1361 break;
1362 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001363 case OMPRTL__kmpc_omp_task_begin_if0: {
1364 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1365 // *new_task);
1366 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1367 CGM.VoidPtrTy};
1368 llvm::FunctionType *FnTy =
1369 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1370 RTLFn =
1371 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1372 break;
1373 }
1374 case OMPRTL__kmpc_omp_task_complete_if0: {
1375 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1376 // *new_task);
1377 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1378 CGM.VoidPtrTy};
1379 llvm::FunctionType *FnTy =
1380 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1381 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1382 /*Name=*/"__kmpc_omp_task_complete_if0");
1383 break;
1384 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001385 case OMPRTL__kmpc_ordered: {
1386 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1387 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1388 llvm::FunctionType *FnTy =
1389 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1390 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1391 break;
1392 }
1393 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001394 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001395 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1396 llvm::FunctionType *FnTy =
1397 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1398 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1399 break;
1400 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001401 case OMPRTL__kmpc_omp_taskwait: {
1402 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1403 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1404 llvm::FunctionType *FnTy =
1405 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1406 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1407 break;
1408 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001409 case OMPRTL__kmpc_taskgroup: {
1410 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1411 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1412 llvm::FunctionType *FnTy =
1413 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1414 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1415 break;
1416 }
1417 case OMPRTL__kmpc_end_taskgroup: {
1418 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1419 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1420 llvm::FunctionType *FnTy =
1421 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1422 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1423 break;
1424 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001425 case OMPRTL__kmpc_push_proc_bind: {
1426 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1427 // int proc_bind)
1428 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1429 llvm::FunctionType *FnTy =
1430 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1431 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1432 break;
1433 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001434 case OMPRTL__kmpc_omp_task_with_deps: {
1435 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1436 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1437 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1438 llvm::Type *TypeParams[] = {
1439 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1440 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1441 llvm::FunctionType *FnTy =
1442 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1443 RTLFn =
1444 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1445 break;
1446 }
1447 case OMPRTL__kmpc_omp_wait_deps: {
1448 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1449 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1450 // kmp_depend_info_t *noalias_dep_list);
1451 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1452 CGM.Int32Ty, CGM.VoidPtrTy,
1453 CGM.Int32Ty, CGM.VoidPtrTy};
1454 llvm::FunctionType *FnTy =
1455 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1456 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1457 break;
1458 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001459 case OMPRTL__kmpc_cancellationpoint: {
1460 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1461 // global_tid, kmp_int32 cncl_kind)
1462 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1463 llvm::FunctionType *FnTy =
1464 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1466 break;
1467 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001468 case OMPRTL__kmpc_cancel: {
1469 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1470 // kmp_int32 cncl_kind)
1471 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1472 llvm::FunctionType *FnTy =
1473 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1474 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1475 break;
1476 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001477 case OMPRTL__kmpc_push_num_teams: {
1478 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1479 // kmp_int32 num_teams, kmp_int32 num_threads)
1480 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1481 CGM.Int32Ty};
1482 llvm::FunctionType *FnTy =
1483 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1484 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1485 break;
1486 }
1487 case OMPRTL__kmpc_fork_teams: {
1488 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1489 // microtask, ...);
1490 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1491 getKmpc_MicroPointerTy()};
1492 llvm::FunctionType *FnTy =
1493 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1494 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1495 break;
1496 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001497 case OMPRTL__kmpc_taskloop: {
1498 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1499 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1500 // sched, kmp_uint64 grainsize, void *task_dup);
1501 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1502 CGM.IntTy,
1503 CGM.VoidPtrTy,
1504 CGM.IntTy,
1505 CGM.Int64Ty->getPointerTo(),
1506 CGM.Int64Ty->getPointerTo(),
1507 CGM.Int64Ty,
1508 CGM.IntTy,
1509 CGM.IntTy,
1510 CGM.Int64Ty,
1511 CGM.VoidPtrTy};
1512 llvm::FunctionType *FnTy =
1513 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1514 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1515 break;
1516 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001517 case OMPRTL__kmpc_doacross_init: {
1518 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1519 // num_dims, struct kmp_dim *dims);
1520 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1521 CGM.Int32Ty,
1522 CGM.Int32Ty,
1523 CGM.VoidPtrTy};
1524 llvm::FunctionType *FnTy =
1525 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1526 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1527 break;
1528 }
1529 case OMPRTL__kmpc_doacross_fini: {
1530 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1531 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1532 llvm::FunctionType *FnTy =
1533 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1534 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1535 break;
1536 }
1537 case OMPRTL__kmpc_doacross_post: {
1538 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1539 // *vec);
1540 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1541 CGM.Int64Ty->getPointerTo()};
1542 llvm::FunctionType *FnTy =
1543 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1544 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1545 break;
1546 }
1547 case OMPRTL__kmpc_doacross_wait: {
1548 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1549 // *vec);
1550 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1551 CGM.Int64Ty->getPointerTo()};
1552 llvm::FunctionType *FnTy =
1553 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1554 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1555 break;
1556 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001557 case OMPRTL__tgt_target: {
1558 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1559 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1560 // *arg_types);
1561 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1562 CGM.VoidPtrTy,
1563 CGM.Int32Ty,
1564 CGM.VoidPtrPtrTy,
1565 CGM.VoidPtrPtrTy,
1566 CGM.SizeTy->getPointerTo(),
1567 CGM.Int32Ty->getPointerTo()};
1568 llvm::FunctionType *FnTy =
1569 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1570 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1571 break;
1572 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001573 case OMPRTL__tgt_target_teams: {
1574 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1575 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1576 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1577 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1578 CGM.VoidPtrTy,
1579 CGM.Int32Ty,
1580 CGM.VoidPtrPtrTy,
1581 CGM.VoidPtrPtrTy,
1582 CGM.SizeTy->getPointerTo(),
1583 CGM.Int32Ty->getPointerTo(),
1584 CGM.Int32Ty,
1585 CGM.Int32Ty};
1586 llvm::FunctionType *FnTy =
1587 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1588 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1589 break;
1590 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001591 case OMPRTL__tgt_register_lib: {
1592 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1593 QualType ParamTy =
1594 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1595 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1596 llvm::FunctionType *FnTy =
1597 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1599 break;
1600 }
1601 case OMPRTL__tgt_unregister_lib: {
1602 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1603 QualType ParamTy =
1604 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1605 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1606 llvm::FunctionType *FnTy =
1607 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1608 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1609 break;
1610 }
Samuel Antaodf158d52016-04-27 22:58:19 +00001611 case OMPRTL__tgt_target_data_begin: {
1612 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1613 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1614 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1615 CGM.Int32Ty,
1616 CGM.VoidPtrPtrTy,
1617 CGM.VoidPtrPtrTy,
1618 CGM.SizeTy->getPointerTo(),
1619 CGM.Int32Ty->getPointerTo()};
1620 llvm::FunctionType *FnTy =
1621 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1622 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1623 break;
1624 }
1625 case OMPRTL__tgt_target_data_end: {
1626 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1627 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1628 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1629 CGM.Int32Ty,
1630 CGM.VoidPtrPtrTy,
1631 CGM.VoidPtrPtrTy,
1632 CGM.SizeTy->getPointerTo(),
1633 CGM.Int32Ty->getPointerTo()};
1634 llvm::FunctionType *FnTy =
1635 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1636 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1637 break;
1638 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00001639 case OMPRTL__tgt_target_data_update: {
1640 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1641 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1642 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1643 CGM.Int32Ty,
1644 CGM.VoidPtrPtrTy,
1645 CGM.VoidPtrPtrTy,
1646 CGM.SizeTy->getPointerTo(),
1647 CGM.Int32Ty->getPointerTo()};
1648 llvm::FunctionType *FnTy =
1649 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1650 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1651 break;
1652 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001653 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001654 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001655 return RTLFn;
1656}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001657
Alexander Musman21212e42015-03-13 10:38:23 +00001658llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1659 bool IVSigned) {
1660 assert((IVSize == 32 || IVSize == 64) &&
1661 "IV size is not compatible with the omp runtime");
1662 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1663 : "__kmpc_for_static_init_4u")
1664 : (IVSigned ? "__kmpc_for_static_init_8"
1665 : "__kmpc_for_static_init_8u");
1666 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1667 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1668 llvm::Type *TypeParams[] = {
1669 getIdentTyPointerTy(), // loc
1670 CGM.Int32Ty, // tid
1671 CGM.Int32Ty, // schedtype
1672 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1673 PtrTy, // p_lower
1674 PtrTy, // p_upper
1675 PtrTy, // p_stride
1676 ITy, // incr
1677 ITy // chunk
1678 };
1679 llvm::FunctionType *FnTy =
1680 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1681 return CGM.CreateRuntimeFunction(FnTy, Name);
1682}
1683
Alexander Musman92bdaab2015-03-12 13:37:50 +00001684llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1685 bool IVSigned) {
1686 assert((IVSize == 32 || IVSize == 64) &&
1687 "IV size is not compatible with the omp runtime");
1688 auto Name =
1689 IVSize == 32
1690 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1691 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1692 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1693 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1694 CGM.Int32Ty, // tid
1695 CGM.Int32Ty, // schedtype
1696 ITy, // lower
1697 ITy, // upper
1698 ITy, // stride
1699 ITy // chunk
1700 };
1701 llvm::FunctionType *FnTy =
1702 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1703 return CGM.CreateRuntimeFunction(FnTy, Name);
1704}
1705
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001706llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1707 bool IVSigned) {
1708 assert((IVSize == 32 || IVSize == 64) &&
1709 "IV size is not compatible with the omp runtime");
1710 auto Name =
1711 IVSize == 32
1712 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1713 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1714 llvm::Type *TypeParams[] = {
1715 getIdentTyPointerTy(), // loc
1716 CGM.Int32Ty, // tid
1717 };
1718 llvm::FunctionType *FnTy =
1719 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1720 return CGM.CreateRuntimeFunction(FnTy, Name);
1721}
1722
Alexander Musman92bdaab2015-03-12 13:37:50 +00001723llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1724 bool IVSigned) {
1725 assert((IVSize == 32 || IVSize == 64) &&
1726 "IV size is not compatible with the omp runtime");
1727 auto Name =
1728 IVSize == 32
1729 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1730 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1731 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1732 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1733 llvm::Type *TypeParams[] = {
1734 getIdentTyPointerTy(), // loc
1735 CGM.Int32Ty, // tid
1736 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1737 PtrTy, // p_lower
1738 PtrTy, // p_upper
1739 PtrTy // p_stride
1740 };
1741 llvm::FunctionType *FnTy =
1742 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1743 return CGM.CreateRuntimeFunction(FnTy, Name);
1744}
1745
Alexey Bataev97720002014-11-11 04:05:39 +00001746llvm::Constant *
1747CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001748 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1749 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001750 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001751 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001752 Twine(CGM.getMangledName(VD)) + ".cache.");
1753}
1754
John McCall7f416cc2015-09-08 08:05:57 +00001755Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1756 const VarDecl *VD,
1757 Address VDAddr,
1758 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001759 if (CGM.getLangOpts().OpenMPUseTLS &&
1760 CGM.getContext().getTargetInfo().isTLSSupported())
1761 return VDAddr;
1762
John McCall7f416cc2015-09-08 08:05:57 +00001763 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001764 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001765 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1766 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001767 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1768 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001769 return Address(CGF.EmitRuntimeCall(
1770 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1771 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001772}
1773
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001774void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001775 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001776 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1777 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1778 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001779 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1780 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001781 OMPLoc);
1782 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1783 // to register constructor/destructor for variable.
1784 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001785 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1786 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001787 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001788 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001789 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001790}
1791
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001792llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001793 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001794 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001795 if (CGM.getLangOpts().OpenMPUseTLS &&
1796 CGM.getContext().getTargetInfo().isTLSSupported())
1797 return nullptr;
1798
Alexey Bataev97720002014-11-11 04:05:39 +00001799 VD = VD->getDefinition(CGM.getContext());
1800 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1801 ThreadPrivateWithDefinition.insert(VD);
1802 QualType ASTTy = VD->getType();
1803
1804 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1805 auto Init = VD->getAnyInitializer();
1806 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1807 // Generate function that re-emits the declaration's initializer into the
1808 // threadprivate copy of the variable VD
1809 CodeGenFunction CtorCGF(CGM);
1810 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00001811 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
1812 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00001813 Args.push_back(&Dst);
1814
John McCallc56a8b32016-03-11 04:30:31 +00001815 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1816 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001817 auto FTy = CGM.getTypes().GetFunctionType(FI);
1818 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001819 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001820 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1821 Args, SourceLocation());
1822 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001823 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001824 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001825 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1826 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1827 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001828 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1829 /*IsInitializer=*/true);
1830 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001831 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001832 CGM.getContext().VoidPtrTy, Dst.getLocation());
1833 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1834 CtorCGF.FinishFunction();
1835 Ctor = Fn;
1836 }
1837 if (VD->getType().isDestructedType() != QualType::DK_none) {
1838 // Generate function that emits destructor call for the threadprivate copy
1839 // of the variable VD
1840 CodeGenFunction DtorCGF(CGM);
1841 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00001842 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
1843 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00001844 Args.push_back(&Dst);
1845
John McCallc56a8b32016-03-11 04:30:31 +00001846 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1847 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001848 auto FTy = CGM.getTypes().GetFunctionType(FI);
1849 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001850 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001851 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001852 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1853 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001854 // Create a scope with an artificial location for the body of this function.
1855 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001856 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1857 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001858 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1859 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001860 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1861 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1862 DtorCGF.FinishFunction();
1863 Dtor = Fn;
1864 }
1865 // Do not emit init function if it is not required.
1866 if (!Ctor && !Dtor)
1867 return nullptr;
1868
1869 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1870 auto CopyCtorTy =
1871 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1872 /*isVarArg=*/false)->getPointerTo();
1873 // Copying constructor for the threadprivate variable.
1874 // Must be NULL - reserved by runtime, but currently it requires that this
1875 // parameter is always NULL. Otherwise it fires assertion.
1876 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1877 if (Ctor == nullptr) {
1878 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1879 /*isVarArg=*/false)->getPointerTo();
1880 Ctor = llvm::Constant::getNullValue(CtorTy);
1881 }
1882 if (Dtor == nullptr) {
1883 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1884 /*isVarArg=*/false)->getPointerTo();
1885 Dtor = llvm::Constant::getNullValue(DtorTy);
1886 }
1887 if (!CGF) {
1888 auto InitFunctionTy =
1889 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1890 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001891 InitFunctionTy, ".__omp_threadprivate_init_.",
1892 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001893 CodeGenFunction InitCGF(CGM);
1894 FunctionArgList ArgList;
1895 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1896 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1897 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001898 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001899 InitCGF.FinishFunction();
1900 return InitFunction;
1901 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001902 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001903 }
1904 return nullptr;
1905}
1906
Alexey Bataev1d677132015-04-22 13:57:31 +00001907/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1908/// function. Here is the logic:
1909/// if (Cond) {
1910/// ThenGen();
1911/// } else {
1912/// ElseGen();
1913/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001914void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1915 const RegionCodeGenTy &ThenGen,
1916 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001917 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1918
1919 // If the condition constant folds and can be elided, try to avoid emitting
1920 // the condition and the dead arm of the if/else.
1921 bool CondConstant;
1922 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001923 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001924 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001925 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001926 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001927 return;
1928 }
1929
1930 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1931 // emit the conditional branch.
1932 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1933 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1934 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1935 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1936
1937 // Emit the 'then' code.
1938 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001939 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001940 CGF.EmitBranch(ContBlock);
1941 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001942 // There is no need to emit line number for unconditional branch.
1943 (void)ApplyDebugLocation::CreateEmpty(CGF);
1944 CGF.EmitBlock(ElseBlock);
1945 ElseGen(CGF);
1946 // There is no need to emit line number for unconditional branch.
1947 (void)ApplyDebugLocation::CreateEmpty(CGF);
1948 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001949 // Emit the continuation block for code after the if.
1950 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001951}
1952
Alexey Bataev1d677132015-04-22 13:57:31 +00001953void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1954 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001955 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001956 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001957 if (!CGF.HaveInsertPoint())
1958 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001959 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001960 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1961 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001962 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001963 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001964 llvm::Value *Args[] = {
1965 RTLoc,
1966 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001967 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001968 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1969 RealArgs.append(std::begin(Args), std::end(Args));
1970 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1971
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001972 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001973 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1974 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001975 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1976 PrePostActionTy &) {
1977 auto &RT = CGF.CGM.getOpenMPRuntime();
1978 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001979 // Build calls:
1980 // __kmpc_serialized_parallel(&Loc, GTid);
1981 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001982 CGF.EmitRuntimeCall(
1983 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001984
Alexey Bataev1d677132015-04-22 13:57:31 +00001985 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001986 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001987 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001988 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1989 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001990 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001991 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1992 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1993 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1994 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001995 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001996
Alexey Bataev1d677132015-04-22 13:57:31 +00001997 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001998 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001999 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002000 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2001 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002002 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002003 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002004 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002005 else {
2006 RegionCodeGenTy ThenRCG(ThenGen);
2007 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002008 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002009}
2010
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002011// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002012// thread-ID variable (it is passed in a first argument of the outlined function
2013// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2014// regular serial code region, get thread ID by calling kmp_int32
2015// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2016// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002017Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2018 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002019 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002020 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002021 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002022 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002023
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002024 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002025 auto Int32Ty =
2026 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2027 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2028 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002029 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002030
2031 return ThreadIDTemp;
2032}
2033
Alexey Bataev97720002014-11-11 04:05:39 +00002034llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002035CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002036 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002037 SmallString<256> Buffer;
2038 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002039 Out << Name;
2040 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002041 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2042 if (Elem.second) {
2043 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002044 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002045 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002046 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002047
David Blaikie13156b62014-11-19 03:06:06 +00002048 return Elem.second = new llvm::GlobalVariable(
2049 CGM.getModule(), Ty, /*IsConstant*/ false,
2050 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2051 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002052}
2053
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002054llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002055 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002056 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002057}
2058
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002059namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002060/// Common pre(post)-action for different OpenMP constructs.
2061class CommonActionTy final : public PrePostActionTy {
2062 llvm::Value *EnterCallee;
2063 ArrayRef<llvm::Value *> EnterArgs;
2064 llvm::Value *ExitCallee;
2065 ArrayRef<llvm::Value *> ExitArgs;
2066 bool Conditional;
2067 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002068
2069public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002070 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2071 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2072 bool Conditional = false)
2073 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2074 ExitArgs(ExitArgs), Conditional(Conditional) {}
2075 void Enter(CodeGenFunction &CGF) override {
2076 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2077 if (Conditional) {
2078 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2079 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2080 ContBlock = CGF.createBasicBlock("omp_if.end");
2081 // Generate the branch (If-stmt)
2082 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2083 CGF.EmitBlock(ThenBlock);
2084 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002085 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002086 void Done(CodeGenFunction &CGF) {
2087 // Emit the rest of blocks/branches
2088 CGF.EmitBranch(ContBlock);
2089 CGF.EmitBlock(ContBlock, true);
2090 }
2091 void Exit(CodeGenFunction &CGF) override {
2092 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002093 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002094};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002095} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002096
2097void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2098 StringRef CriticalName,
2099 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002100 SourceLocation Loc, const Expr *Hint) {
2101 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002102 // CriticalOpGen();
2103 // __kmpc_end_critical(ident_t *, gtid, Lock);
2104 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002105 if (!CGF.HaveInsertPoint())
2106 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002107 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2108 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002109 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2110 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002111 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002112 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2113 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2114 }
2115 CommonActionTy Action(
2116 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2117 : OMPRTL__kmpc_critical),
2118 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2119 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002120 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002121}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002122
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002123void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002124 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002125 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002126 if (!CGF.HaveInsertPoint())
2127 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002128 // if(__kmpc_master(ident_t *, gtid)) {
2129 // MasterOpGen();
2130 // __kmpc_end_master(ident_t *, gtid);
2131 // }
2132 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002133 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002134 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2135 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2136 /*Conditional=*/true);
2137 MasterOpGen.setAction(Action);
2138 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2139 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002140}
2141
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002142void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2143 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002144 if (!CGF.HaveInsertPoint())
2145 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002146 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2147 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002148 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002149 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002150 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002151 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2152 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002153}
2154
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002155void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2156 const RegionCodeGenTy &TaskgroupOpGen,
2157 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002158 if (!CGF.HaveInsertPoint())
2159 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002160 // __kmpc_taskgroup(ident_t *, gtid);
2161 // TaskgroupOpGen();
2162 // __kmpc_end_taskgroup(ident_t *, gtid);
2163 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002164 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2165 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2166 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2167 Args);
2168 TaskgroupOpGen.setAction(Action);
2169 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002170}
2171
John McCall7f416cc2015-09-08 08:05:57 +00002172/// Given an array of pointers to variables, project the address of a
2173/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002174static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2175 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002176 // Pull out the pointer to the variable.
2177 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002178 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002179 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2180
2181 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002182 Addr = CGF.Builder.CreateElementBitCast(
2183 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002184 return Addr;
2185}
2186
Alexey Bataeva63048e2015-03-23 06:18:07 +00002187static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002188 CodeGenModule &CGM, llvm::Type *ArgsType,
2189 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2190 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002191 auto &C = CGM.getContext();
2192 // void copy_func(void *LHSArg, void *RHSArg);
2193 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002194 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2195 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002196 Args.push_back(&LHSArg);
2197 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002198 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002199 auto *Fn = llvm::Function::Create(
2200 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2201 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002202 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002203 CodeGenFunction CGF(CGM);
2204 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002205 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002206 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002207 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2208 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2209 ArgsType), CGF.getPointerAlign());
2210 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2211 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2212 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002213 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2214 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2215 // ...
2216 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002217 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002218 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2219 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2220
2221 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2222 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2223
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002224 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2225 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002226 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002227 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002228 CGF.FinishFunction();
2229 return Fn;
2230}
2231
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002232void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002233 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002234 SourceLocation Loc,
2235 ArrayRef<const Expr *> CopyprivateVars,
2236 ArrayRef<const Expr *> SrcExprs,
2237 ArrayRef<const Expr *> DstExprs,
2238 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002239 if (!CGF.HaveInsertPoint())
2240 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002241 assert(CopyprivateVars.size() == SrcExprs.size() &&
2242 CopyprivateVars.size() == DstExprs.size() &&
2243 CopyprivateVars.size() == AssignmentOps.size());
2244 auto &C = CGM.getContext();
2245 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002246 // if(__kmpc_single(ident_t *, gtid)) {
2247 // SingleOpGen();
2248 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002249 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002250 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002251 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2252 // <copy_func>, did_it);
2253
John McCall7f416cc2015-09-08 08:05:57 +00002254 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002255 if (!CopyprivateVars.empty()) {
2256 // int32 did_it = 0;
2257 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2258 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002259 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002260 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002261 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002262 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002263 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2264 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2265 /*Conditional=*/true);
2266 SingleOpGen.setAction(Action);
2267 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2268 if (DidIt.isValid()) {
2269 // did_it = 1;
2270 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2271 }
2272 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002273 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2274 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002275 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002276 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2277 auto CopyprivateArrayTy =
2278 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2279 /*IndexTypeQuals=*/0);
2280 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002281 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002282 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2283 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002284 Address Elem = CGF.Builder.CreateConstArrayGEP(
2285 CopyprivateList, I, CGF.getPointerSize());
2286 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002287 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002288 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2289 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002290 }
2291 // Build function that copies private values from single region to all other
2292 // threads in the corresponding parallel region.
2293 auto *CpyFn = emitCopyprivateCopyFunction(
2294 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002295 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002296 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002297 Address CL =
2298 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2299 CGF.VoidPtrTy);
2300 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002301 llvm::Value *Args[] = {
2302 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2303 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002304 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002305 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002306 CpyFn, // void (*) (void *, void *) <copy_func>
2307 DidItVal // i32 did_it
2308 };
2309 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2310 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002311}
2312
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002313void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2314 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002315 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002316 if (!CGF.HaveInsertPoint())
2317 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002318 // __kmpc_ordered(ident_t *, gtid);
2319 // OrderedOpGen();
2320 // __kmpc_end_ordered(ident_t *, gtid);
2321 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002322 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002323 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002324 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2325 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2326 Args);
2327 OrderedOpGen.setAction(Action);
2328 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2329 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002330 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002331 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002332}
2333
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002334void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002335 OpenMPDirectiveKind Kind, bool EmitChecks,
2336 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002337 if (!CGF.HaveInsertPoint())
2338 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002339 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002340 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002341 unsigned Flags;
2342 if (Kind == OMPD_for)
2343 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2344 else if (Kind == OMPD_sections)
2345 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2346 else if (Kind == OMPD_single)
2347 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2348 else if (Kind == OMPD_barrier)
2349 Flags = OMP_IDENT_BARRIER_EXPL;
2350 else
2351 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002352 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2353 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002354 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2355 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002356 if (auto *OMPRegionInfo =
2357 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002358 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002359 auto *Result = CGF.EmitRuntimeCall(
2360 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002361 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002362 // if (__kmpc_cancel_barrier()) {
2363 // exit from construct;
2364 // }
2365 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2366 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2367 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2368 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2369 CGF.EmitBlock(ExitBB);
2370 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002371 auto CancelDestination =
2372 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002373 CGF.EmitBranchThroughCleanup(CancelDestination);
2374 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2375 }
2376 return;
2377 }
2378 }
2379 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002380}
2381
Alexander Musmanc6388682014-12-15 07:07:06 +00002382/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2383static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002384 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002385 switch (ScheduleKind) {
2386 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002387 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2388 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002389 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002390 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002391 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002392 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002393 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002394 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2395 case OMPC_SCHEDULE_auto:
2396 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002397 case OMPC_SCHEDULE_unknown:
2398 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002399 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002400 }
2401 llvm_unreachable("Unexpected runtime schedule");
2402}
2403
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002404/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2405static OpenMPSchedType
2406getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2407 // only static is allowed for dist_schedule
2408 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2409}
2410
Alexander Musmanc6388682014-12-15 07:07:06 +00002411bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2412 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002413 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002414 return Schedule == OMP_sch_static;
2415}
2416
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002417bool CGOpenMPRuntime::isStaticNonchunked(
2418 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2419 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2420 return Schedule == OMP_dist_sch_static;
2421}
2422
2423
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002424bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002425 auto Schedule =
2426 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002427 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2428 return Schedule != OMP_sch_static;
2429}
2430
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002431static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2432 OpenMPScheduleClauseModifier M1,
2433 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002434 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002435 switch (M1) {
2436 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002437 Modifier = OMP_sch_modifier_monotonic;
2438 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002439 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002440 Modifier = OMP_sch_modifier_nonmonotonic;
2441 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002442 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002443 if (Schedule == OMP_sch_static_chunked)
2444 Schedule = OMP_sch_static_balanced_chunked;
2445 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002446 case OMPC_SCHEDULE_MODIFIER_last:
2447 case OMPC_SCHEDULE_MODIFIER_unknown:
2448 break;
2449 }
2450 switch (M2) {
2451 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002452 Modifier = OMP_sch_modifier_monotonic;
2453 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002454 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002455 Modifier = OMP_sch_modifier_nonmonotonic;
2456 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002457 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002458 if (Schedule == OMP_sch_static_chunked)
2459 Schedule = OMP_sch_static_balanced_chunked;
2460 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002461 case OMPC_SCHEDULE_MODIFIER_last:
2462 case OMPC_SCHEDULE_MODIFIER_unknown:
2463 break;
2464 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002465 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002466}
2467
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002468void CGOpenMPRuntime::emitForDispatchInit(
2469 CodeGenFunction &CGF, SourceLocation Loc,
2470 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2471 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002472 if (!CGF.HaveInsertPoint())
2473 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002474 OpenMPSchedType Schedule = getRuntimeSchedule(
2475 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002476 assert(Ordered ||
2477 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002478 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2479 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002480 // Call __kmpc_dispatch_init(
2481 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2482 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2483 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002484
John McCall7f416cc2015-09-08 08:05:57 +00002485 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002486 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2487 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002488 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002489 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2490 CGF.Builder.getInt32(addMonoNonMonoModifier(
2491 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002492 DispatchValues.LB, // Lower
2493 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002494 CGF.Builder.getIntN(IVSize, 1), // Stride
2495 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002496 };
2497 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2498}
2499
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002500static void emitForStaticInitCall(
2501 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2502 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2503 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2504 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2505 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002506 if (!CGF.HaveInsertPoint())
2507 return;
2508
2509 assert(!Ordered);
2510 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002511 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002512 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2513 Schedule == OMP_dist_sch_static ||
2514 Schedule == OMP_dist_sch_static_chunked);
2515
2516 // Call __kmpc_for_static_init(
2517 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2518 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2519 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2520 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2521 if (Chunk == nullptr) {
2522 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2523 Schedule == OMP_dist_sch_static) &&
2524 "expected static non-chunked schedule");
2525 // If the Chunk was not specified in the clause - use default value 1.
2526 Chunk = CGF.Builder.getIntN(IVSize, 1);
2527 } else {
2528 assert((Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002529 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002530 Schedule == OMP_ord_static_chunked ||
2531 Schedule == OMP_dist_sch_static_chunked) &&
2532 "expected static chunked schedule");
2533 }
2534 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002535 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2536 Schedule, M1, M2)), // Schedule type
2537 IL.getPointer(), // &isLastIter
2538 LB.getPointer(), // &LB
2539 UB.getPointer(), // &UB
2540 ST.getPointer(), // &Stride
2541 CGF.Builder.getIntN(IVSize, 1), // Incr
2542 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002543 };
2544 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2545}
2546
John McCall7f416cc2015-09-08 08:05:57 +00002547void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2548 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002549 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002550 unsigned IVSize, bool IVSigned,
2551 bool Ordered, Address IL, Address LB,
2552 Address UB, Address ST,
2553 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002554 OpenMPSchedType ScheduleNum =
2555 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002556 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2557 auto *ThreadId = getThreadID(CGF, Loc);
2558 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002559 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2560 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2561 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002562}
John McCall7f416cc2015-09-08 08:05:57 +00002563
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002564void CGOpenMPRuntime::emitDistributeStaticInit(
2565 CodeGenFunction &CGF, SourceLocation Loc,
2566 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2567 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002568 llvm::Value *Chunk) {
2569 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2570 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2571 auto *ThreadId = getThreadID(CGF, Loc);
2572 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002573 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2574 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2575 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2576 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002577}
2578
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002579void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2580 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002581 if (!CGF.HaveInsertPoint())
2582 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002583 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002584 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002585 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2586 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002587}
2588
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002589void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2590 SourceLocation Loc,
2591 unsigned IVSize,
2592 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002593 if (!CGF.HaveInsertPoint())
2594 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002595 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002596 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002597 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2598}
2599
Alexander Musman92bdaab2015-03-12 13:37:50 +00002600llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2601 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002602 bool IVSigned, Address IL,
2603 Address LB, Address UB,
2604 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002605 // Call __kmpc_dispatch_next(
2606 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2607 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2608 // kmp_int[32|64] *p_stride);
2609 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002610 emitUpdateLocation(CGF, Loc),
2611 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002612 IL.getPointer(), // &isLastIter
2613 LB.getPointer(), // &Lower
2614 UB.getPointer(), // &Upper
2615 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002616 };
2617 llvm::Value *Call =
2618 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2619 return CGF.EmitScalarConversion(
2620 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002621 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002622}
2623
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002624void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2625 llvm::Value *NumThreads,
2626 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002627 if (!CGF.HaveInsertPoint())
2628 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002629 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2630 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002631 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002632 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002633 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2634 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002635}
2636
Alexey Bataev7f210c62015-06-18 13:40:03 +00002637void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2638 OpenMPProcBindClauseKind ProcBind,
2639 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002640 if (!CGF.HaveInsertPoint())
2641 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002642 // Constants for proc bind value accepted by the runtime.
2643 enum ProcBindTy {
2644 ProcBindFalse = 0,
2645 ProcBindTrue,
2646 ProcBindMaster,
2647 ProcBindClose,
2648 ProcBindSpread,
2649 ProcBindIntel,
2650 ProcBindDefault
2651 } RuntimeProcBind;
2652 switch (ProcBind) {
2653 case OMPC_PROC_BIND_master:
2654 RuntimeProcBind = ProcBindMaster;
2655 break;
2656 case OMPC_PROC_BIND_close:
2657 RuntimeProcBind = ProcBindClose;
2658 break;
2659 case OMPC_PROC_BIND_spread:
2660 RuntimeProcBind = ProcBindSpread;
2661 break;
2662 case OMPC_PROC_BIND_unknown:
2663 llvm_unreachable("Unsupported proc_bind value.");
2664 }
2665 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2666 llvm::Value *Args[] = {
2667 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2668 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2669 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2670}
2671
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002672void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2673 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002674 if (!CGF.HaveInsertPoint())
2675 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002676 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002677 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2678 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002679}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002680
Alexey Bataev62b63b12015-03-10 07:28:44 +00002681namespace {
2682/// \brief Indexes of fields for type kmp_task_t.
2683enum KmpTaskTFields {
2684 /// \brief List of shared variables.
2685 KmpTaskTShareds,
2686 /// \brief Task routine.
2687 KmpTaskTRoutine,
2688 /// \brief Partition id for the untied tasks.
2689 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00002690 /// Function with call of destructors for private variables.
2691 Data1,
2692 /// Task priority.
2693 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00002694 /// (Taskloops only) Lower bound.
2695 KmpTaskTLowerBound,
2696 /// (Taskloops only) Upper bound.
2697 KmpTaskTUpperBound,
2698 /// (Taskloops only) Stride.
2699 KmpTaskTStride,
2700 /// (Taskloops only) Is last iteration flag.
2701 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002702};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002703} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002704
Samuel Antaoee8fb302016-01-06 13:42:12 +00002705bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2706 // FIXME: Add other entries type when they become supported.
2707 return OffloadEntriesTargetRegion.empty();
2708}
2709
2710/// \brief Initialize target region entry.
2711void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2712 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2713 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002714 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002715 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2716 "only required for the device "
2717 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002718 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00002719 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
2720 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002721 ++OffloadingEntriesNum;
2722}
2723
2724void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2725 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2726 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002727 llvm::Constant *Addr, llvm::Constant *ID,
2728 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002729 // If we are emitting code for a target, the entry is already initialized,
2730 // only has to be registered.
2731 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002732 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002733 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002734 auto &Entry =
2735 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002736 assert(Entry.isValid() && "Entry not initialized!");
2737 Entry.setAddress(Addr);
2738 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002739 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002740 return;
2741 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00002742 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00002743 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002744 }
2745}
2746
2747bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002748 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2749 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002750 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2751 if (PerDevice == OffloadEntriesTargetRegion.end())
2752 return false;
2753 auto PerFile = PerDevice->second.find(FileID);
2754 if (PerFile == PerDevice->second.end())
2755 return false;
2756 auto PerParentName = PerFile->second.find(ParentName);
2757 if (PerParentName == PerFile->second.end())
2758 return false;
2759 auto PerLine = PerParentName->second.find(LineNum);
2760 if (PerLine == PerParentName->second.end())
2761 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002762 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002763 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002764 return false;
2765 return true;
2766}
2767
2768void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2769 const OffloadTargetRegionEntryInfoActTy &Action) {
2770 // Scan all target region entries and perform the provided action.
2771 for (auto &D : OffloadEntriesTargetRegion)
2772 for (auto &F : D.second)
2773 for (auto &P : F.second)
2774 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002775 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002776}
2777
2778/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2779/// \a Codegen. This is used to emit the two functions that register and
2780/// unregister the descriptor of the current compilation unit.
2781static llvm::Function *
2782createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2783 const RegionCodeGenTy &Codegen) {
2784 auto &C = CGM.getContext();
2785 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002786 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002787 Args.push_back(&DummyPtr);
2788
2789 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00002790 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002791 auto FTy = CGM.getTypes().GetFunctionType(FI);
2792 auto *Fn =
2793 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2794 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2795 Codegen(CGF);
2796 CGF.FinishFunction();
2797 return Fn;
2798}
2799
2800llvm::Function *
2801CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2802
2803 // If we don't have entries or if we are emitting code for the device, we
2804 // don't need to do anything.
2805 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2806 return nullptr;
2807
2808 auto &M = CGM.getModule();
2809 auto &C = CGM.getContext();
2810
2811 // Get list of devices we care about
2812 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2813
2814 // We should be creating an offloading descriptor only if there are devices
2815 // specified.
2816 assert(!Devices.empty() && "No OpenMP offloading devices??");
2817
2818 // Create the external variables that will point to the begin and end of the
2819 // host entries section. These will be defined by the linker.
2820 auto *OffloadEntryTy =
2821 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2822 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2823 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002824 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002825 ".omp_offloading.entries_begin");
2826 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2827 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002828 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002829 ".omp_offloading.entries_end");
2830
2831 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00002832 auto *DeviceImageTy = cast<llvm::StructType>(
2833 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002834 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002835 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002836
2837 for (unsigned i = 0; i < Devices.size(); ++i) {
2838 StringRef T = Devices[i].getTriple();
2839 auto *ImgBegin = new llvm::GlobalVariable(
2840 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002841 /*Initializer=*/nullptr,
2842 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002843 auto *ImgEnd = new llvm::GlobalVariable(
2844 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002845 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002846
John McCall6c9f1fdb2016-11-19 08:17:24 +00002847 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2848 Dev.add(ImgBegin);
2849 Dev.add(ImgEnd);
2850 Dev.add(HostEntriesBegin);
2851 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00002852 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002853 }
2854
2855 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002856 llvm::GlobalVariable *DeviceImages =
2857 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2858 CGM.getPointerAlign(),
2859 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002860 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002861
2862 // This is a Zero array to be used in the creation of the constant expressions
2863 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2864 llvm::Constant::getNullValue(CGM.Int32Ty)};
2865
2866 // Create the target region descriptor.
2867 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2868 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002869 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002870 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2871 DescInit.addInt(CGM.Int32Ty, Devices.size());
2872 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2873 DeviceImages,
2874 Index));
2875 DescInit.add(HostEntriesBegin);
2876 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002877
John McCall6c9f1fdb2016-11-19 08:17:24 +00002878 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2879 CGM.getPointerAlign(),
2880 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002881
2882 // Emit code to register or unregister the descriptor at execution
2883 // startup or closing, respectively.
2884
2885 // Create a variable to drive the registration and unregistration of the
2886 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2887 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2888 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00002889 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002890
2891 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002892 CGM, ".omp_offloading.descriptor_unreg",
2893 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002894 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2895 Desc);
2896 });
2897 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002898 CGM, ".omp_offloading.descriptor_reg",
2899 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002900 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2901 Desc);
2902 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2903 });
George Rokos29d0f002017-05-27 03:03:13 +00002904 if (CGM.supportsCOMDAT()) {
2905 // It is sufficient to call registration function only once, so create a
2906 // COMDAT group for registration/unregistration functions and associated
2907 // data. That would reduce startup time and code size. Registration
2908 // function serves as a COMDAT group key.
2909 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
2910 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
2911 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
2912 RegFn->setComdat(ComdatKey);
2913 UnRegFn->setComdat(ComdatKey);
2914 DeviceImages->setComdat(ComdatKey);
2915 Desc->setComdat(ComdatKey);
2916 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002917 return RegFn;
2918}
2919
Samuel Antao2de62b02016-02-13 23:35:10 +00002920void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002921 llvm::Constant *Addr, uint64_t Size,
2922 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002923 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002924 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2925 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2926 llvm::LLVMContext &C = CGM.getModule().getContext();
2927 llvm::Module &M = CGM.getModule();
2928
2929 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002930 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002931
2932 // Create constant string with the name.
2933 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2934
2935 llvm::GlobalVariable *Str =
2936 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2937 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2938 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002939 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002940 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2941
John McCall6c9f1fdb2016-11-19 08:17:24 +00002942 // We can't have any padding between symbols, so we need to have 1-byte
2943 // alignment.
2944 auto Align = CharUnits::fromQuantity(1);
2945
Samuel Antaoee8fb302016-01-06 13:42:12 +00002946 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00002947 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002948 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2949 EntryInit.add(AddrPtr);
2950 EntryInit.add(StrPtr);
2951 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002952 EntryInit.addInt(CGM.Int32Ty, Flags);
2953 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002954 llvm::GlobalVariable *Entry =
2955 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2956 Align,
2957 /*constant*/ true,
2958 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002959
2960 // The entry has to be created in the section the linker expects it to be.
2961 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00002962}
2963
2964void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2965 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00002966 // can easily figure out what to emit. The produced metadata looks like
2967 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00002968 //
2969 // !omp_offload.info = !{!1, ...}
2970 //
2971 // Right now we only generate metadata for function that contain target
2972 // regions.
2973
2974 // If we do not have entries, we dont need to do anything.
2975 if (OffloadEntriesInfoManager.empty())
2976 return;
2977
2978 llvm::Module &M = CGM.getModule();
2979 llvm::LLVMContext &C = M.getContext();
2980 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2981 OrderedEntries(OffloadEntriesInfoManager.size());
2982
2983 // Create the offloading info metadata node.
2984 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2985
Simon Pilgrim2c518802017-03-30 14:13:19 +00002986 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002987 auto getMDInt = [&](unsigned v) {
2988 return llvm::ConstantAsMetadata::get(
2989 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2990 };
2991
2992 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2993
2994 // Create function that emits metadata for each target region entry;
2995 auto &&TargetRegionMetadataEmitter = [&](
2996 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002997 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2998 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2999 // Generate metadata for target regions. Each entry of this metadata
3000 // contains:
3001 // - Entry 0 -> Kind of this type of metadata (0).
3002 // - Entry 1 -> Device ID of the file where the entry was identified.
3003 // - Entry 2 -> File ID of the file where the entry was identified.
3004 // - Entry 3 -> Mangled name of the function where the entry was identified.
3005 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003006 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003007 // The first element of the metadata node is the kind.
3008 Ops.push_back(getMDInt(E.getKind()));
3009 Ops.push_back(getMDInt(DeviceID));
3010 Ops.push_back(getMDInt(FileID));
3011 Ops.push_back(getMDString(ParentName));
3012 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003013 Ops.push_back(getMDInt(E.getOrder()));
3014
3015 // Save this entry in the right position of the ordered entries array.
3016 OrderedEntries[E.getOrder()] = &E;
3017
3018 // Add metadata to the named metadata node.
3019 MD->addOperand(llvm::MDNode::get(C, Ops));
3020 };
3021
3022 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3023 TargetRegionMetadataEmitter);
3024
3025 for (auto *E : OrderedEntries) {
3026 assert(E && "All ordered entries must exist!");
3027 if (auto *CE =
3028 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3029 E)) {
3030 assert(CE->getID() && CE->getAddress() &&
3031 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003032 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003033 } else
3034 llvm_unreachable("Unsupported entry kind.");
3035 }
3036}
3037
3038/// \brief Loads all the offload entries information from the host IR
3039/// metadata.
3040void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3041 // If we are in target mode, load the metadata from the host IR. This code has
3042 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3043
3044 if (!CGM.getLangOpts().OpenMPIsDevice)
3045 return;
3046
3047 if (CGM.getLangOpts().OMPHostIRFile.empty())
3048 return;
3049
3050 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3051 if (Buf.getError())
3052 return;
3053
3054 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003055 auto ME = expectedToErrorOrAndEmitErrors(
3056 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003057
3058 if (ME.getError())
3059 return;
3060
3061 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3062 if (!MD)
3063 return;
3064
3065 for (auto I : MD->operands()) {
3066 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3067
3068 auto getMDInt = [&](unsigned Idx) {
3069 llvm::ConstantAsMetadata *V =
3070 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3071 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3072 };
3073
3074 auto getMDString = [&](unsigned Idx) {
3075 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3076 return V->getString();
3077 };
3078
3079 switch (getMDInt(0)) {
3080 default:
3081 llvm_unreachable("Unexpected metadata!");
3082 break;
3083 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3084 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3085 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3086 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3087 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003088 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003089 break;
3090 }
3091 }
3092}
3093
Alexey Bataev62b63b12015-03-10 07:28:44 +00003094void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3095 if (!KmpRoutineEntryPtrTy) {
3096 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3097 auto &C = CGM.getContext();
3098 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3099 FunctionProtoType::ExtProtoInfo EPI;
3100 KmpRoutineEntryPtrQTy = C.getPointerType(
3101 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3102 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3103 }
3104}
3105
Alexey Bataevc71a4092015-09-11 10:29:41 +00003106static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3107 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003108 auto *Field = FieldDecl::Create(
3109 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3110 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3111 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3112 Field->setAccess(AS_public);
3113 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003114 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003115}
3116
Samuel Antaoee8fb302016-01-06 13:42:12 +00003117QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3118
3119 // Make sure the type of the entry is already created. This is the type we
3120 // have to create:
3121 // struct __tgt_offload_entry{
3122 // void *addr; // Pointer to the offload entry info.
3123 // // (function or global)
3124 // char *name; // Name of the function or global.
3125 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003126 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3127 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003128 // };
3129 if (TgtOffloadEntryQTy.isNull()) {
3130 ASTContext &C = CGM.getContext();
3131 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3132 RD->startDefinition();
3133 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3134 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3135 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003136 addFieldToRecordDecl(
3137 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3138 addFieldToRecordDecl(
3139 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003140 RD->completeDefinition();
3141 TgtOffloadEntryQTy = C.getRecordType(RD);
3142 }
3143 return TgtOffloadEntryQTy;
3144}
3145
3146QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3147 // These are the types we need to build:
3148 // struct __tgt_device_image{
3149 // void *ImageStart; // Pointer to the target code start.
3150 // void *ImageEnd; // Pointer to the target code end.
3151 // // We also add the host entries to the device image, as it may be useful
3152 // // for the target runtime to have access to that information.
3153 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3154 // // the entries.
3155 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3156 // // entries (non inclusive).
3157 // };
3158 if (TgtDeviceImageQTy.isNull()) {
3159 ASTContext &C = CGM.getContext();
3160 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3161 RD->startDefinition();
3162 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3163 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3164 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3165 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3166 RD->completeDefinition();
3167 TgtDeviceImageQTy = C.getRecordType(RD);
3168 }
3169 return TgtDeviceImageQTy;
3170}
3171
3172QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3173 // struct __tgt_bin_desc{
3174 // int32_t NumDevices; // Number of devices supported.
3175 // __tgt_device_image *DeviceImages; // Arrays of device images
3176 // // (one per device).
3177 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3178 // // entries.
3179 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3180 // // entries (non inclusive).
3181 // };
3182 if (TgtBinaryDescriptorQTy.isNull()) {
3183 ASTContext &C = CGM.getContext();
3184 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3185 RD->startDefinition();
3186 addFieldToRecordDecl(
3187 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3188 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3189 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3190 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3191 RD->completeDefinition();
3192 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3193 }
3194 return TgtBinaryDescriptorQTy;
3195}
3196
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003197namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003198struct PrivateHelpersTy {
3199 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3200 const VarDecl *PrivateElemInit)
3201 : Original(Original), PrivateCopy(PrivateCopy),
3202 PrivateElemInit(PrivateElemInit) {}
3203 const VarDecl *Original;
3204 const VarDecl *PrivateCopy;
3205 const VarDecl *PrivateElemInit;
3206};
3207typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003208} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003209
Alexey Bataev9e034042015-05-05 04:05:12 +00003210static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003211createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003212 if (!Privates.empty()) {
3213 auto &C = CGM.getContext();
3214 // Build struct .kmp_privates_t. {
3215 // /* private vars */
3216 // };
3217 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3218 RD->startDefinition();
3219 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003220 auto *VD = Pair.second.Original;
3221 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003222 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003223 auto *FD = addFieldToRecordDecl(C, RD, Type);
3224 if (VD->hasAttrs()) {
3225 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3226 E(VD->getAttrs().end());
3227 I != E; ++I)
3228 FD->addAttr(*I);
3229 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003230 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003231 RD->completeDefinition();
3232 return RD;
3233 }
3234 return nullptr;
3235}
3236
Alexey Bataev9e034042015-05-05 04:05:12 +00003237static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003238createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3239 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003240 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003241 auto &C = CGM.getContext();
3242 // Build struct kmp_task_t {
3243 // void * shareds;
3244 // kmp_routine_entry_t routine;
3245 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003246 // kmp_cmplrdata_t data1;
3247 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003248 // For taskloops additional fields:
3249 // kmp_uint64 lb;
3250 // kmp_uint64 ub;
3251 // kmp_int64 st;
3252 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003253 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003254 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3255 UD->startDefinition();
3256 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3257 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3258 UD->completeDefinition();
3259 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003260 auto *RD = C.buildImplicitRecord("kmp_task_t");
3261 RD->startDefinition();
3262 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3263 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3264 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003265 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3266 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003267 if (isOpenMPTaskLoopDirective(Kind)) {
3268 QualType KmpUInt64Ty =
3269 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3270 QualType KmpInt64Ty =
3271 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3272 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3273 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3274 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3275 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3276 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003277 RD->completeDefinition();
3278 return RD;
3279}
3280
3281static RecordDecl *
3282createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003283 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003284 auto &C = CGM.getContext();
3285 // Build struct kmp_task_t_with_privates {
3286 // kmp_task_t task_data;
3287 // .kmp_privates_t. privates;
3288 // };
3289 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3290 RD->startDefinition();
3291 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003292 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3293 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3294 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003295 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003296 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003297}
3298
3299/// \brief Emit a proxy function which accepts kmp_task_t as the second
3300/// argument.
3301/// \code
3302/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003303/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003304/// For taskloops:
3305/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003306/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003307/// return 0;
3308/// }
3309/// \endcode
3310static llvm::Value *
3311emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003312 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3313 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003314 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003315 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3316 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003317 auto &C = CGM.getContext();
3318 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003319 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3320 ImplicitParamDecl::Other);
3321 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3322 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3323 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003324 Args.push_back(&GtidArg);
3325 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003326 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003327 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003328 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3329 auto *TaskEntry =
3330 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3331 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003332 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003333 CodeGenFunction CGF(CGM);
3334 CGF.disableDebugInfo();
3335 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3336
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003337 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003338 // tt,
3339 // For taskloops:
3340 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3341 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003342 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003343 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003344 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3345 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3346 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003347 auto *KmpTaskTWithPrivatesQTyRD =
3348 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003349 LValue Base =
3350 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003351 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3352 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3353 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003354 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003355
3356 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3357 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003358 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003359 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003360 CGF.ConvertTypeForMem(SharedsPtrTy));
3361
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003362 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3363 llvm::Value *PrivatesParam;
3364 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3365 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3366 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003367 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003368 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003369 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003370
Alexey Bataev7292c292016-04-25 12:22:29 +00003371 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3372 TaskPrivatesMap,
3373 CGF.Builder
3374 .CreatePointerBitCastOrAddrSpaceCast(
3375 TDBase.getAddress(), CGF.VoidPtrTy)
3376 .getPointer()};
3377 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3378 std::end(CommonArgs));
3379 if (isOpenMPTaskLoopDirective(Kind)) {
3380 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3381 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3382 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3383 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3384 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3385 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3386 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3387 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3388 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3389 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3390 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3391 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3392 CallArgs.push_back(LBParam);
3393 CallArgs.push_back(UBParam);
3394 CallArgs.push_back(StParam);
3395 CallArgs.push_back(LIParam);
3396 }
3397 CallArgs.push_back(SharedsParam);
3398
Alexey Bataev62b63b12015-03-10 07:28:44 +00003399 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3400 CGF.EmitStoreThroughLValue(
3401 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003402 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003403 CGF.FinishFunction();
3404 return TaskEntry;
3405}
3406
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003407static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3408 SourceLocation Loc,
3409 QualType KmpInt32Ty,
3410 QualType KmpTaskTWithPrivatesPtrQTy,
3411 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003412 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003413 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003414 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3415 ImplicitParamDecl::Other);
3416 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3417 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3418 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003419 Args.push_back(&GtidArg);
3420 Args.push_back(&TaskTypeArg);
3421 FunctionType::ExtInfo Info;
3422 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003423 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003424 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3425 auto *DestructorFn =
3426 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3427 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003428 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3429 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003430 CodeGenFunction CGF(CGM);
3431 CGF.disableDebugInfo();
3432 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3433 Args);
3434
Alexey Bataev31300ed2016-02-04 11:27:03 +00003435 LValue Base = CGF.EmitLoadOfPointerLValue(
3436 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3437 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003438 auto *KmpTaskTWithPrivatesQTyRD =
3439 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3440 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003441 Base = CGF.EmitLValueForField(Base, *FI);
3442 for (auto *Field :
3443 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3444 if (auto DtorKind = Field->getType().isDestructedType()) {
3445 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3446 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3447 }
3448 }
3449 CGF.FinishFunction();
3450 return DestructorFn;
3451}
3452
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003453/// \brief Emit a privates mapping function for correct handling of private and
3454/// firstprivate variables.
3455/// \code
3456/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3457/// **noalias priv1,..., <tyn> **noalias privn) {
3458/// *priv1 = &.privates.priv1;
3459/// ...;
3460/// *privn = &.privates.privn;
3461/// }
3462/// \endcode
3463static llvm::Value *
3464emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003465 ArrayRef<const Expr *> PrivateVars,
3466 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003467 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003468 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003469 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003470 auto &C = CGM.getContext();
3471 FunctionArgList Args;
3472 ImplicitParamDecl TaskPrivatesArg(
3473 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003474 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3475 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003476 Args.push_back(&TaskPrivatesArg);
3477 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3478 unsigned Counter = 1;
3479 for (auto *E: PrivateVars) {
3480 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003481 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3482 C.getPointerType(C.getPointerType(E->getType()))
3483 .withConst()
3484 .withRestrict(),
3485 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003486 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3487 PrivateVarsPos[VD] = Counter;
3488 ++Counter;
3489 }
3490 for (auto *E : FirstprivateVars) {
3491 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003492 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3493 C.getPointerType(C.getPointerType(E->getType()))
3494 .withConst()
3495 .withRestrict(),
3496 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003497 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3498 PrivateVarsPos[VD] = Counter;
3499 ++Counter;
3500 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003501 for (auto *E: LastprivateVars) {
3502 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003503 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3504 C.getPointerType(C.getPointerType(E->getType()))
3505 .withConst()
3506 .withRestrict(),
3507 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003508 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3509 PrivateVarsPos[VD] = Counter;
3510 ++Counter;
3511 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003512 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003513 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003514 auto *TaskPrivatesMapTy =
3515 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3516 auto *TaskPrivatesMap = llvm::Function::Create(
3517 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3518 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003519 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3520 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00003521 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00003522 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003523 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003524 CodeGenFunction CGF(CGM);
3525 CGF.disableDebugInfo();
3526 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3527 TaskPrivatesMapFnInfo, Args);
3528
3529 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003530 LValue Base = CGF.EmitLoadOfPointerLValue(
3531 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3532 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003533 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3534 Counter = 0;
3535 for (auto *Field : PrivatesQTyRD->fields()) {
3536 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3537 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003538 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003539 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3540 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003541 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003542 ++Counter;
3543 }
3544 CGF.FinishFunction();
3545 return TaskPrivatesMap;
3546}
3547
Alexey Bataev9e034042015-05-05 04:05:12 +00003548static int array_pod_sort_comparator(const PrivateDataTy *P1,
3549 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003550 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3551}
3552
Alexey Bataevf93095a2016-05-05 08:46:22 +00003553/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00003554static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003555 const OMPExecutableDirective &D,
3556 Address KmpTaskSharedsPtr, LValue TDBase,
3557 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3558 QualType SharedsTy, QualType SharedsPtrTy,
3559 const OMPTaskDataTy &Data,
3560 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3561 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003562 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3563 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3564 LValue SrcBase;
3565 if (!Data.FirstprivateVars.empty()) {
3566 SrcBase = CGF.MakeAddrLValue(
3567 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3568 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3569 SharedsTy);
3570 }
3571 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3572 cast<CapturedStmt>(*D.getAssociatedStmt()));
3573 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3574 for (auto &&Pair : Privates) {
3575 auto *VD = Pair.second.PrivateCopy;
3576 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003577 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3578 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003579 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003580 if (auto *Elem = Pair.second.PrivateElemInit) {
3581 auto *OriginalVD = Pair.second.Original;
3582 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3583 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3584 SharedRefLValue = CGF.MakeAddrLValue(
3585 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003586 SharedRefLValue.getType(),
3587 LValueBaseInfo(AlignmentSource::Decl,
3588 SharedRefLValue.getBaseInfo().getMayAlias()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003589 QualType Type = OriginalVD->getType();
3590 if (Type->isArrayType()) {
3591 // Initialize firstprivate array.
3592 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3593 // Perform simple memcpy.
3594 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3595 SharedRefLValue.getAddress(), Type);
3596 } else {
3597 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00003598 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00003599 CGF.EmitOMPAggregateAssign(
3600 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3601 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3602 Address SrcElement) {
3603 // Clean up any temporaries needed by the initialization.
3604 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3605 InitScope.addPrivate(
3606 Elem, [SrcElement]() -> Address { return SrcElement; });
3607 (void)InitScope.Privatize();
3608 // Emit initialization for single element.
3609 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3610 CGF, &CapturesInfo);
3611 CGF.EmitAnyExprToMem(Init, DestElement,
3612 Init->getType().getQualifiers(),
3613 /*IsInitializer=*/false);
3614 });
3615 }
3616 } else {
3617 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3618 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3619 return SharedRefLValue.getAddress();
3620 });
3621 (void)InitScope.Privatize();
3622 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3623 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3624 /*capturedByInit=*/false);
3625 }
3626 } else
3627 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3628 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003629 ++FI;
3630 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003631}
3632
3633/// Check if duplication function is required for taskloops.
3634static bool checkInitIsRequired(CodeGenFunction &CGF,
3635 ArrayRef<PrivateDataTy> Privates) {
3636 bool InitRequired = false;
3637 for (auto &&Pair : Privates) {
3638 auto *VD = Pair.second.PrivateCopy;
3639 auto *Init = VD->getAnyInitializer();
3640 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3641 !CGF.isTrivialInitializer(Init));
3642 }
3643 return InitRequired;
3644}
3645
3646
3647/// Emit task_dup function (for initialization of
3648/// private/firstprivate/lastprivate vars and last_iter flag)
3649/// \code
3650/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3651/// lastpriv) {
3652/// // setup lastprivate flag
3653/// task_dst->last = lastpriv;
3654/// // could be constructor calls here...
3655/// }
3656/// \endcode
3657static llvm::Value *
3658emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3659 const OMPExecutableDirective &D,
3660 QualType KmpTaskTWithPrivatesPtrQTy,
3661 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3662 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3663 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3664 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3665 auto &C = CGM.getContext();
3666 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003667 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3668 KmpTaskTWithPrivatesPtrQTy,
3669 ImplicitParamDecl::Other);
3670 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3671 KmpTaskTWithPrivatesPtrQTy,
3672 ImplicitParamDecl::Other);
3673 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3674 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003675 Args.push_back(&DstArg);
3676 Args.push_back(&SrcArg);
3677 Args.push_back(&LastprivArg);
3678 auto &TaskDupFnInfo =
3679 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3680 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3681 auto *TaskDup =
3682 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3683 ".omp_task_dup.", &CGM.getModule());
3684 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3685 CodeGenFunction CGF(CGM);
3686 CGF.disableDebugInfo();
3687 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3688
3689 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3690 CGF.GetAddrOfLocalVar(&DstArg),
3691 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3692 // task_dst->liter = lastpriv;
3693 if (WithLastIter) {
3694 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3695 LValue Base = CGF.EmitLValueForField(
3696 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3697 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3698 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3699 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3700 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3701 }
3702
3703 // Emit initial values for private copies (if any).
3704 assert(!Privates.empty());
3705 Address KmpTaskSharedsPtr = Address::invalid();
3706 if (!Data.FirstprivateVars.empty()) {
3707 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3708 CGF.GetAddrOfLocalVar(&SrcArg),
3709 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3710 LValue Base = CGF.EmitLValueForField(
3711 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3712 KmpTaskSharedsPtr = Address(
3713 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3714 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3715 KmpTaskTShareds)),
3716 Loc),
3717 CGF.getNaturalTypeAlignment(SharedsTy));
3718 }
Alexey Bataev8a831592016-05-10 10:36:51 +00003719 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3720 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003721 CGF.FinishFunction();
3722 return TaskDup;
3723}
3724
Alexey Bataev8a831592016-05-10 10:36:51 +00003725/// Checks if destructor function is required to be generated.
3726/// \return true if cleanups are required, false otherwise.
3727static bool
3728checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3729 bool NeedsCleanup = false;
3730 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3731 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3732 for (auto *FD : PrivateRD->fields()) {
3733 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3734 if (NeedsCleanup)
3735 break;
3736 }
3737 return NeedsCleanup;
3738}
3739
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003740CGOpenMPRuntime::TaskResultTy
3741CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3742 const OMPExecutableDirective &D,
3743 llvm::Value *TaskFunction, QualType SharedsTy,
3744 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003745 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003746 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003747 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003748 auto I = Data.PrivateCopies.begin();
3749 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003750 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3751 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003752 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003753 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3754 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003755 ++I;
3756 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003757 I = Data.FirstprivateCopies.begin();
3758 auto IElemInitRef = Data.FirstprivateInits.begin();
3759 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003760 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3761 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003762 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003763 PrivateHelpersTy(
3764 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3765 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003766 ++I;
3767 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003768 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003769 I = Data.LastprivateCopies.begin();
3770 for (auto *E : Data.LastprivateVars) {
3771 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3772 Privates.push_back(std::make_pair(
3773 C.getDeclAlign(VD),
3774 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3775 /*PrivateElemInit=*/nullptr)));
3776 ++I;
3777 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003778 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3779 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003780 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3781 // Build type kmp_routine_entry_t (if not built yet).
3782 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003783 // Build type kmp_task_t (if not built yet).
3784 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003785 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3786 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003787 }
3788 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003789 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003790 auto *KmpTaskTWithPrivatesQTyRD =
3791 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3792 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3793 QualType KmpTaskTWithPrivatesPtrQTy =
3794 C.getPointerType(KmpTaskTWithPrivatesQTy);
3795 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3796 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003797 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003798 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3799
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003800 // Emit initial values for private copies (if any).
3801 llvm::Value *TaskPrivatesMap = nullptr;
3802 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00003803 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003804 if (!Privates.empty()) {
3805 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003806 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3807 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3808 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003809 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3810 TaskPrivatesMap, TaskPrivatesMapTy);
3811 } else {
3812 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3813 cast<llvm::PointerType>(TaskPrivatesMapTy));
3814 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003815 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3816 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003817 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003818 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3819 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3820 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003821
3822 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3823 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3824 // kmp_routine_entry_t *task_entry);
3825 // Task flags. Format is taken from
3826 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3827 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003828 enum {
3829 TiedFlag = 0x1,
3830 FinalFlag = 0x2,
3831 DestructorsFlag = 0x8,
3832 PriorityFlag = 0x20
3833 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003834 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00003835 bool NeedsCleanup = false;
3836 if (!Privates.empty()) {
3837 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3838 if (NeedsCleanup)
3839 Flags = Flags | DestructorsFlag;
3840 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003841 if (Data.Priority.getInt())
3842 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003843 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003844 Data.Final.getPointer()
3845 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00003846 CGF.Builder.getInt32(FinalFlag),
3847 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003848 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003849 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003850 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003851 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3852 getThreadID(CGF, Loc), TaskFlags,
3853 KmpTaskTWithPrivatesTySize, SharedsSize,
3854 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3855 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003856 auto *NewTask = CGF.EmitRuntimeCall(
3857 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003858 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3859 NewTask, KmpTaskTWithPrivatesPtrTy);
3860 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3861 KmpTaskTWithPrivatesQTy);
3862 LValue TDBase =
3863 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003864 // Fill the data in the resulting kmp_task_t record.
3865 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003866 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003867 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003868 KmpTaskSharedsPtr =
3869 Address(CGF.EmitLoadOfScalar(
3870 CGF.EmitLValueForField(
3871 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3872 KmpTaskTShareds)),
3873 Loc),
3874 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003875 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003876 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003877 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00003878 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003879 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003880 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3881 SharedsTy, SharedsPtrTy, Data, Privates,
3882 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003883 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3884 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3885 Result.TaskDupFn = emitTaskDupFunction(
3886 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3887 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3888 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003889 }
3890 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00003891 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3892 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00003893 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00003894 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3895 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3896 if (NeedsCleanup) {
3897 llvm::Value *DestructorFn = emitDestructorsFunction(
3898 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3899 KmpTaskTWithPrivatesQTy);
3900 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3901 LValue DestructorsLV = CGF.EmitLValueForField(
3902 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3903 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3904 DestructorFn, KmpRoutineEntryPtrTy),
3905 DestructorsLV);
3906 }
3907 // Set priority.
3908 if (Data.Priority.getInt()) {
3909 LValue Data2LV = CGF.EmitLValueForField(
3910 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3911 LValue PriorityLV = CGF.EmitLValueForField(
3912 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3913 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3914 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003915 Result.NewTask = NewTask;
3916 Result.TaskEntry = TaskEntry;
3917 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3918 Result.TDBase = TDBase;
3919 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3920 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00003921}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003922
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003923void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3924 const OMPExecutableDirective &D,
3925 llvm::Value *TaskFunction,
3926 QualType SharedsTy, Address Shareds,
3927 const Expr *IfCond,
3928 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003929 if (!CGF.HaveInsertPoint())
3930 return;
3931
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003932 TaskResultTy Result =
3933 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3934 llvm::Value *NewTask = Result.NewTask;
3935 llvm::Value *TaskEntry = Result.TaskEntry;
3936 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3937 LValue TDBase = Result.TDBase;
3938 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00003939 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003940 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003941 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003942 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00003943 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003944 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003945 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003946 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3947 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003948 QualType FlagsTy =
3949 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003950 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3951 if (KmpDependInfoTy.isNull()) {
3952 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3953 KmpDependInfoRD->startDefinition();
3954 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3955 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3956 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3957 KmpDependInfoRD->completeDefinition();
3958 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003959 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003960 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003961 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003962 // Define type kmp_depend_info[<Dependences.size()>];
3963 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003964 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003965 ArrayType::Normal, /*IndexTypeQuals=*/0);
3966 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003967 DependenciesArray =
3968 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003969 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003970 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00003971 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003972 llvm::Value *Size;
3973 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003974 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3975 LValue UpAddrLVal =
3976 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3977 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003978 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003979 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003980 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003981 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3982 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003983 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003984 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003985 auto Base = CGF.MakeAddrLValue(
3986 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003987 KmpDependInfoTy);
3988 // deps[i].base_addr = &<Dependences[i].second>;
3989 auto BaseAddrLVal = CGF.EmitLValueForField(
3990 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003991 CGF.EmitStoreOfScalar(
3992 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3993 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003994 // deps[i].len = sizeof(<Dependences[i].second>);
3995 auto LenLVal = CGF.EmitLValueForField(
3996 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3997 CGF.EmitStoreOfScalar(Size, LenLVal);
3998 // deps[i].flags = <Dependences[i].first>;
3999 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004000 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004001 case OMPC_DEPEND_in:
4002 DepKind = DepIn;
4003 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004004 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004005 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004006 case OMPC_DEPEND_inout:
4007 DepKind = DepInOut;
4008 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004009 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004010 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004011 case OMPC_DEPEND_unknown:
4012 llvm_unreachable("Unknown task dependence type");
4013 }
4014 auto FlagsLVal = CGF.EmitLValueForField(
4015 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4016 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4017 FlagsLVal);
4018 }
John McCall7f416cc2015-09-08 08:05:57 +00004019 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4020 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004021 CGF.VoidPtrTy);
4022 }
4023
Alexey Bataev62b63b12015-03-10 07:28:44 +00004024 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4025 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004026 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4027 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4028 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4029 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004030 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004031 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004032 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4033 llvm::Value *DepTaskArgs[7];
4034 if (NumDependencies) {
4035 DepTaskArgs[0] = UpLoc;
4036 DepTaskArgs[1] = ThreadID;
4037 DepTaskArgs[2] = NewTask;
4038 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4039 DepTaskArgs[4] = DependenciesArray.getPointer();
4040 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4041 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4042 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004043 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4044 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004045 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004046 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004047 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4048 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4049 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4050 }
John McCall7f416cc2015-09-08 08:05:57 +00004051 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004052 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004053 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004054 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004055 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004056 TaskArgs);
4057 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004058 // Check if parent region is untied and build return for untied task;
4059 if (auto *Region =
4060 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4061 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004062 };
John McCall7f416cc2015-09-08 08:05:57 +00004063
4064 llvm::Value *DepWaitTaskArgs[6];
4065 if (NumDependencies) {
4066 DepWaitTaskArgs[0] = UpLoc;
4067 DepWaitTaskArgs[1] = ThreadID;
4068 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4069 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4070 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4071 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4072 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004073 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4074 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4075 PrePostActionTy &) {
4076 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004077 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4078 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4079 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4080 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4081 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004082 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004083 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004084 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004085 // Call proxy_task_entry(gtid, new_task);
4086 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4087 CodeGenFunction &CGF, PrePostActionTy &Action) {
4088 Action.Enter(CGF);
4089 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4090 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4091 };
4092
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004093 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4094 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004095 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4096 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004097 RegionCodeGenTy RCG(CodeGen);
4098 CommonActionTy Action(
4099 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4100 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4101 RCG.setAction(Action);
4102 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004103 };
John McCall7f416cc2015-09-08 08:05:57 +00004104
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004105 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004106 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004107 else {
4108 RegionCodeGenTy ThenRCG(ThenCodeGen);
4109 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004110 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004111}
4112
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004113void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4114 const OMPLoopDirective &D,
4115 llvm::Value *TaskFunction,
4116 QualType SharedsTy, Address Shareds,
4117 const Expr *IfCond,
4118 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004119 if (!CGF.HaveInsertPoint())
4120 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004121 TaskResultTy Result =
4122 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004123 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4124 // libcall.
4125 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4126 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4127 // sched, kmp_uint64 grainsize, void *task_dup);
4128 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4129 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4130 llvm::Value *IfVal;
4131 if (IfCond) {
4132 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4133 /*isSigned=*/true);
4134 } else
4135 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4136
4137 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004138 Result.TDBase,
4139 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004140 auto *LBVar =
4141 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4142 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4143 /*IsInitializer=*/true);
4144 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004145 Result.TDBase,
4146 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004147 auto *UBVar =
4148 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4149 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4150 /*IsInitializer=*/true);
4151 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004152 Result.TDBase,
4153 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004154 auto *StVar =
4155 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4156 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4157 /*IsInitializer=*/true);
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004158 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004159 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004160 UpLoc,
4161 ThreadID,
4162 Result.NewTask,
4163 IfVal,
4164 LBLVal.getPointer(),
4165 UBLVal.getPointer(),
4166 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4167 llvm::ConstantInt::getNullValue(
4168 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004169 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004170 CGF.IntTy, Data.Schedule.getPointer()
4171 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004172 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004173 Data.Schedule.getPointer()
4174 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004175 /*isSigned=*/false)
4176 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004177 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4178 Result.TaskDupFn, CGF.VoidPtrTy)
4179 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004180 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4181}
4182
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004183/// \brief Emit reduction operation for each element of array (required for
4184/// array sections) LHS op = RHS.
4185/// \param Type Type of array.
4186/// \param LHSVar Variable on the left side of the reduction operation
4187/// (references element of array in original variable).
4188/// \param RHSVar Variable on the right side of the reduction operation
4189/// (references element of array in original variable).
4190/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4191/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004192static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004193 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4194 const VarDecl *RHSVar,
4195 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4196 const Expr *, const Expr *)> &RedOpGen,
4197 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4198 const Expr *UpExpr = nullptr) {
4199 // Perform element-by-element initialization.
4200 QualType ElementTy;
4201 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4202 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4203
4204 // Drill down to the base element type on both arrays.
4205 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4206 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4207
4208 auto RHSBegin = RHSAddr.getPointer();
4209 auto LHSBegin = LHSAddr.getPointer();
4210 // Cast from pointer to array type to pointer to single element.
4211 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4212 // The basic structure here is a while-do loop.
4213 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4214 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4215 auto IsEmpty =
4216 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4217 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4218
4219 // Enter the loop body, making that address the current address.
4220 auto EntryBB = CGF.Builder.GetInsertBlock();
4221 CGF.EmitBlock(BodyBB);
4222
4223 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4224
4225 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4226 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4227 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4228 Address RHSElementCurrent =
4229 Address(RHSElementPHI,
4230 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4231
4232 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4233 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4234 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4235 Address LHSElementCurrent =
4236 Address(LHSElementPHI,
4237 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4238
4239 // Emit copy.
4240 CodeGenFunction::OMPPrivateScope Scope(CGF);
4241 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4242 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4243 Scope.Privatize();
4244 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4245 Scope.ForceCleanup();
4246
4247 // Shift the address forward by one element.
4248 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4249 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4250 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4251 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4252 // Check whether we've reached the end.
4253 auto Done =
4254 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4255 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4256 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4257 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4258
4259 // Done.
4260 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4261}
4262
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004263/// Emit reduction combiner. If the combiner is a simple expression emit it as
4264/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4265/// UDR combiner function.
4266static void emitReductionCombiner(CodeGenFunction &CGF,
4267 const Expr *ReductionOp) {
4268 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4269 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4270 if (auto *DRE =
4271 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4272 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4273 std::pair<llvm::Function *, llvm::Function *> Reduction =
4274 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4275 RValue Func = RValue::get(Reduction.first);
4276 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4277 CGF.EmitIgnoredExpr(ReductionOp);
4278 return;
4279 }
4280 CGF.EmitIgnoredExpr(ReductionOp);
4281}
4282
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004283llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4284 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4285 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4286 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004287 auto &C = CGM.getContext();
4288
4289 // void reduction_func(void *LHSArg, void *RHSArg);
4290 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004291 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4292 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004293 Args.push_back(&LHSArg);
4294 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004295 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004296 auto *Fn = llvm::Function::Create(
4297 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4298 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004299 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004300 CodeGenFunction CGF(CGM);
4301 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4302
4303 // Dst = (void*[n])(LHSArg);
4304 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004305 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4306 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4307 ArgsType), CGF.getPointerAlign());
4308 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4309 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4310 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004311
4312 // ...
4313 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4314 // ...
4315 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004316 auto IPriv = Privates.begin();
4317 unsigned Idx = 0;
4318 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004319 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4320 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004321 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004322 });
4323 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4324 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004325 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004326 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004327 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004328 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004329 // Get array size and emit VLA type.
4330 ++Idx;
4331 Address Elem =
4332 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4333 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004334 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4335 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004336 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004337 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004338 CGF.EmitVariablyModifiedType(PrivTy);
4339 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004340 }
4341 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004342 IPriv = Privates.begin();
4343 auto ILHS = LHSExprs.begin();
4344 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004345 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004346 if ((*IPriv)->getType()->isArrayType()) {
4347 // Emit reduction for array section.
4348 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4349 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004350 EmitOMPAggregateReduction(
4351 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4352 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4353 emitReductionCombiner(CGF, E);
4354 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004355 } else
4356 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004357 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004358 ++IPriv;
4359 ++ILHS;
4360 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004361 }
4362 Scope.ForceCleanup();
4363 CGF.FinishFunction();
4364 return Fn;
4365}
4366
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004367void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4368 const Expr *ReductionOp,
4369 const Expr *PrivateRef,
4370 const DeclRefExpr *LHS,
4371 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004372 if (PrivateRef->getType()->isArrayType()) {
4373 // Emit reduction for array section.
4374 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4375 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4376 EmitOMPAggregateReduction(
4377 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4378 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4379 emitReductionCombiner(CGF, ReductionOp);
4380 });
4381 } else
4382 // Emit reduction for array subscript or single variable.
4383 emitReductionCombiner(CGF, ReductionOp);
4384}
4385
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004386void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004387 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004388 ArrayRef<const Expr *> LHSExprs,
4389 ArrayRef<const Expr *> RHSExprs,
4390 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004391 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004392 if (!CGF.HaveInsertPoint())
4393 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004394
4395 bool WithNowait = Options.WithNowait;
4396 bool SimpleReduction = Options.SimpleReduction;
4397
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004398 // Next code should be emitted for reduction:
4399 //
4400 // static kmp_critical_name lock = { 0 };
4401 //
4402 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4403 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4404 // ...
4405 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4406 // *(Type<n>-1*)rhs[<n>-1]);
4407 // }
4408 //
4409 // ...
4410 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4411 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4412 // RedList, reduce_func, &<lock>)) {
4413 // case 1:
4414 // ...
4415 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4416 // ...
4417 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4418 // break;
4419 // case 2:
4420 // ...
4421 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4422 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004423 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004424 // break;
4425 // default:;
4426 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004427 //
4428 // if SimpleReduction is true, only the next code is generated:
4429 // ...
4430 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4431 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004432
4433 auto &C = CGM.getContext();
4434
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004435 if (SimpleReduction) {
4436 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004437 auto IPriv = Privates.begin();
4438 auto ILHS = LHSExprs.begin();
4439 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004440 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004441 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4442 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004443 ++IPriv;
4444 ++ILHS;
4445 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004446 }
4447 return;
4448 }
4449
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004450 // 1. Build a list of reduction variables.
4451 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004452 auto Size = RHSExprs.size();
4453 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004454 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004455 // Reserve place for array size.
4456 ++Size;
4457 }
4458 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004459 QualType ReductionArrayTy =
4460 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4461 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004462 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004463 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004464 auto IPriv = Privates.begin();
4465 unsigned Idx = 0;
4466 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004467 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004468 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004469 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004470 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004471 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4472 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004473 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004474 // Store array size.
4475 ++Idx;
4476 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4477 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004478 llvm::Value *Size = CGF.Builder.CreateIntCast(
4479 CGF.getVLASize(
4480 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4481 .first,
4482 CGF.SizeTy, /*isSigned=*/false);
4483 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4484 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004485 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004486 }
4487
4488 // 2. Emit reduce_func().
4489 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004490 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4491 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004492
4493 // 3. Create static kmp_critical_name lock = { 0 };
4494 auto *Lock = getCriticalRegionLock(".reduction");
4495
4496 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4497 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004498 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004499 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004500 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004501 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4502 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004503 llvm::Value *Args[] = {
4504 IdentTLoc, // ident_t *<loc>
4505 ThreadId, // i32 <gtid>
4506 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4507 ReductionArrayTySize, // size_type sizeof(RedList)
4508 RL, // void *RedList
4509 ReductionFn, // void (*) (void *, void *) <reduce_func>
4510 Lock // kmp_critical_name *&<lock>
4511 };
4512 auto Res = CGF.EmitRuntimeCall(
4513 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4514 : OMPRTL__kmpc_reduce),
4515 Args);
4516
4517 // 5. Build switch(res)
4518 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4519 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4520
4521 // 6. Build case 1:
4522 // ...
4523 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4524 // ...
4525 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4526 // break;
4527 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4528 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4529 CGF.EmitBlock(Case1BB);
4530
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004531 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4532 llvm::Value *EndArgs[] = {
4533 IdentTLoc, // ident_t *<loc>
4534 ThreadId, // i32 <gtid>
4535 Lock // kmp_critical_name *&<lock>
4536 };
4537 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4538 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004539 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004540 auto IPriv = Privates.begin();
4541 auto ILHS = LHSExprs.begin();
4542 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004543 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004544 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4545 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004546 ++IPriv;
4547 ++ILHS;
4548 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004549 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004550 };
4551 RegionCodeGenTy RCG(CodeGen);
4552 CommonActionTy Action(
4553 nullptr, llvm::None,
4554 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4555 : OMPRTL__kmpc_end_reduce),
4556 EndArgs);
4557 RCG.setAction(Action);
4558 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004559
4560 CGF.EmitBranch(DefaultBB);
4561
4562 // 7. Build case 2:
4563 // ...
4564 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4565 // ...
4566 // break;
4567 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4568 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4569 CGF.EmitBlock(Case2BB);
4570
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004571 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4572 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004573 auto ILHS = LHSExprs.begin();
4574 auto IRHS = RHSExprs.begin();
4575 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004576 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004577 const Expr *XExpr = nullptr;
4578 const Expr *EExpr = nullptr;
4579 const Expr *UpExpr = nullptr;
4580 BinaryOperatorKind BO = BO_Comma;
4581 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4582 if (BO->getOpcode() == BO_Assign) {
4583 XExpr = BO->getLHS();
4584 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004585 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004586 }
4587 // Try to emit update expression as a simple atomic.
4588 auto *RHSExpr = UpExpr;
4589 if (RHSExpr) {
4590 // Analyze RHS part of the whole expression.
4591 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4592 RHSExpr->IgnoreParenImpCasts())) {
4593 // If this is a conditional operator, analyze its condition for
4594 // min/max reduction operator.
4595 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004596 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004597 if (auto *BORHS =
4598 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4599 EExpr = BORHS->getRHS();
4600 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004601 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004602 }
4603 if (XExpr) {
4604 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004605 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004606 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4607 const Expr *EExpr, const Expr *UpExpr) {
4608 LValue X = CGF.EmitLValue(XExpr);
4609 RValue E;
4610 if (EExpr)
4611 E = CGF.EmitAnyExpr(EExpr);
4612 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004613 X, E, BO, /*IsXLHSInRHSPart=*/true,
4614 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004615 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004616 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4617 PrivateScope.addPrivate(
4618 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4619 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4620 CGF.emitOMPSimpleStore(
4621 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4622 VD->getType().getNonReferenceType(), Loc);
4623 return LHSTemp;
4624 });
4625 (void)PrivateScope.Privatize();
4626 return CGF.EmitAnyExpr(UpExpr);
4627 });
4628 };
4629 if ((*IPriv)->getType()->isArrayType()) {
4630 // Emit atomic reduction for array section.
4631 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4632 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4633 AtomicRedGen, XExpr, EExpr, UpExpr);
4634 } else
4635 // Emit atomic reduction for array subscript or single variable.
4636 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4637 } else {
4638 // Emit as a critical region.
4639 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4640 const Expr *, const Expr *) {
4641 auto &RT = CGF.CGM.getOpenMPRuntime();
4642 RT.emitCriticalRegion(
4643 CGF, ".atomic_reduction",
4644 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4645 Action.Enter(CGF);
4646 emitReductionCombiner(CGF, E);
4647 },
4648 Loc);
4649 };
4650 if ((*IPriv)->getType()->isArrayType()) {
4651 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4652 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4653 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4654 CritRedGen);
4655 } else
4656 CritRedGen(CGF, nullptr, nullptr, nullptr);
4657 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004658 ++ILHS;
4659 ++IRHS;
4660 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004661 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004662 };
4663 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4664 if (!WithNowait) {
4665 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4666 llvm::Value *EndArgs[] = {
4667 IdentTLoc, // ident_t *<loc>
4668 ThreadId, // i32 <gtid>
4669 Lock // kmp_critical_name *&<lock>
4670 };
4671 CommonActionTy Action(nullptr, llvm::None,
4672 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4673 EndArgs);
4674 AtomicRCG.setAction(Action);
4675 AtomicRCG(CGF);
4676 } else
4677 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004678
4679 CGF.EmitBranch(DefaultBB);
4680 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4681}
4682
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004683void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4684 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004685 if (!CGF.HaveInsertPoint())
4686 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004687 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4688 // global_tid);
4689 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4690 // Ignore return result until untied tasks are supported.
4691 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004692 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4693 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004694}
4695
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004696void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004697 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004698 const RegionCodeGenTy &CodeGen,
4699 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004700 if (!CGF.HaveInsertPoint())
4701 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004702 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004703 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004704}
4705
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004706namespace {
4707enum RTCancelKind {
4708 CancelNoreq = 0,
4709 CancelParallel = 1,
4710 CancelLoop = 2,
4711 CancelSections = 3,
4712 CancelTaskgroup = 4
4713};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004714} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004715
4716static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4717 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004718 if (CancelRegion == OMPD_parallel)
4719 CancelKind = CancelParallel;
4720 else if (CancelRegion == OMPD_for)
4721 CancelKind = CancelLoop;
4722 else if (CancelRegion == OMPD_sections)
4723 CancelKind = CancelSections;
4724 else {
4725 assert(CancelRegion == OMPD_taskgroup);
4726 CancelKind = CancelTaskgroup;
4727 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004728 return CancelKind;
4729}
4730
4731void CGOpenMPRuntime::emitCancellationPointCall(
4732 CodeGenFunction &CGF, SourceLocation Loc,
4733 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004734 if (!CGF.HaveInsertPoint())
4735 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004736 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4737 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004738 if (auto *OMPRegionInfo =
4739 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00004740 // For 'cancellation point taskgroup', the task region info may not have a
4741 // cancel. This may instead happen in another adjacent task.
4742 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004743 llvm::Value *Args[] = {
4744 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4745 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004746 // Ignore return result until untied tasks are supported.
4747 auto *Result = CGF.EmitRuntimeCall(
4748 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4749 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004750 // exit from construct;
4751 // }
4752 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4753 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4754 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4755 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4756 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004757 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004758 auto CancelDest =
4759 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004760 CGF.EmitBranchThroughCleanup(CancelDest);
4761 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4762 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004763 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004764}
4765
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004766void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004767 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004768 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004769 if (!CGF.HaveInsertPoint())
4770 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004771 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4772 // kmp_int32 cncl_kind);
4773 if (auto *OMPRegionInfo =
4774 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004775 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4776 PrePostActionTy &) {
4777 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004778 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004779 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004780 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4781 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004782 auto *Result = CGF.EmitRuntimeCall(
4783 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004784 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004785 // exit from construct;
4786 // }
4787 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4788 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4789 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4790 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4791 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00004792 // exit from construct;
4793 auto CancelDest =
4794 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4795 CGF.EmitBranchThroughCleanup(CancelDest);
4796 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4797 };
4798 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004799 emitOMPIfClause(CGF, IfCond, ThenGen,
4800 [](CodeGenFunction &, PrePostActionTy &) {});
4801 else {
4802 RegionCodeGenTy ThenRCG(ThenGen);
4803 ThenRCG(CGF);
4804 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004805 }
4806}
Samuel Antaobed3c462015-10-02 16:14:20 +00004807
Samuel Antaoee8fb302016-01-06 13:42:12 +00004808/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004809/// consists of the file and device IDs as well as line number associated with
4810/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004811static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4812 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004813 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004814
4815 auto &SM = C.getSourceManager();
4816
4817 // The loc should be always valid and have a file ID (the user cannot use
4818 // #pragma directives in macros)
4819
4820 assert(Loc.isValid() && "Source location is expected to be always valid.");
4821 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4822
4823 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4824 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4825
4826 llvm::sys::fs::UniqueID ID;
4827 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4828 llvm_unreachable("Source file with target region no longer exists!");
4829
4830 DeviceID = ID.getDevice();
4831 FileID = ID.getFile();
4832 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004833}
4834
4835void CGOpenMPRuntime::emitTargetOutlinedFunction(
4836 const OMPExecutableDirective &D, StringRef ParentName,
4837 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004838 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004839 assert(!ParentName.empty() && "Invalid target region parent name!");
4840
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004841 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4842 IsOffloadEntry, CodeGen);
4843}
4844
4845void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4846 const OMPExecutableDirective &D, StringRef ParentName,
4847 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4848 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004849 // Create a unique name for the entry function using the source location
4850 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004851 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004852 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004853 //
4854 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004855 // mangled name of the function that encloses the target region and BB is the
4856 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004857
4858 unsigned DeviceID;
4859 unsigned FileID;
4860 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004861 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004862 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004863 SmallString<64> EntryFnName;
4864 {
4865 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004866 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4867 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004868 }
4869
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004870 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4871
Samuel Antaobed3c462015-10-02 16:14:20 +00004872 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004873 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004874 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004875
Samuel Antao6d004262016-06-16 18:39:34 +00004876 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004877
4878 // If this target outline function is not an offload entry, we don't need to
4879 // register it.
4880 if (!IsOffloadEntry)
4881 return;
4882
4883 // The target region ID is used by the runtime library to identify the current
4884 // target region, so it only has to be unique and not necessarily point to
4885 // anything. It could be the pointer to the outlined function that implements
4886 // the target region, but we aren't using that so that the compiler doesn't
4887 // need to keep that, and could therefore inline the host function if proven
4888 // worthwhile during optimization. In the other hand, if emitting code for the
4889 // device, the ID has to be the function address so that it can retrieved from
4890 // the offloading entry and launched by the runtime library. We also mark the
4891 // outlined function to have external linkage in case we are emitting code for
4892 // the device, because these functions will be entry points to the device.
4893
4894 if (CGM.getLangOpts().OpenMPIsDevice) {
4895 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4896 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4897 } else
4898 OutlinedFnID = new llvm::GlobalVariable(
4899 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4900 llvm::GlobalValue::PrivateLinkage,
4901 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4902
4903 // Register the information for the entry associated with this target region.
4904 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00004905 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
4906 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00004907}
4908
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004909/// discard all CompoundStmts intervening between two constructs
4910static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4911 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4912 Body = CS->body_front();
4913
4914 return Body;
4915}
4916
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004917/// Emit the number of teams for a target directive. Inspect the num_teams
4918/// clause associated with a teams construct combined or closely nested
4919/// with the target directive.
4920///
4921/// Emit a team of size one for directives such as 'target parallel' that
4922/// have no associated teams construct.
4923///
4924/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00004925static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004926emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4927 CodeGenFunction &CGF,
4928 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004929
4930 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4931 "teams directive expected to be "
4932 "emitted only for the host!");
4933
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004934 auto &Bld = CGF.Builder;
4935
4936 // If the target directive is combined with a teams directive:
4937 // Return the value in the num_teams clause, if any.
4938 // Otherwise, return 0 to denote the runtime default.
4939 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
4940 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
4941 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
4942 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
4943 /*IgnoreResultAssign*/ true);
4944 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
4945 /*IsSigned=*/true);
4946 }
4947
4948 // The default value is 0.
4949 return Bld.getInt32(0);
4950 }
4951
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004952 // If the target directive is combined with a parallel directive but not a
4953 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004954 if (isOpenMPParallelDirective(D.getDirectiveKind()))
4955 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004956
4957 // If the current target region has a teams region enclosed, we need to get
4958 // the number of teams to pass to the runtime function call. This is done
4959 // by generating the expression in a inlined region. This is required because
4960 // the expression is captured in the enclosing target environment when the
4961 // teams directive is not combined with target.
4962
4963 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4964
4965 // FIXME: Accommodate other combined directives with teams when they become
4966 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004967 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4968 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004969 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4970 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4971 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4972 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004973 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
4974 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004975 }
4976
4977 // If we have an enclosed teams directive but no num_teams clause we use
4978 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004979 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004980 }
4981
4982 // No teams associated with the directive.
4983 return nullptr;
4984}
4985
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004986/// Emit the number of threads for a target directive. Inspect the
4987/// thread_limit clause associated with a teams construct combined or closely
4988/// nested with the target directive.
4989///
4990/// Emit the num_threads clause for directives such as 'target parallel' that
4991/// have no associated teams construct.
4992///
4993/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00004994static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004995emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4996 CodeGenFunction &CGF,
4997 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004998
4999 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5000 "teams directive expected to be "
5001 "emitted only for the host!");
5002
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005003 auto &Bld = CGF.Builder;
5004
5005 //
5006 // If the target directive is combined with a teams directive:
5007 // Return the value in the thread_limit clause, if any.
5008 //
5009 // If the target directive is combined with a parallel directive:
5010 // Return the value in the num_threads clause, if any.
5011 //
5012 // If both clauses are set, select the minimum of the two.
5013 //
5014 // If neither teams or parallel combined directives set the number of threads
5015 // in a team, return 0 to denote the runtime default.
5016 //
5017 // If this is not a teams directive return nullptr.
5018
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005019 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5020 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005021 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5022 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005023 llvm::Value *ThreadLimitVal = nullptr;
5024
5025 if (const auto *ThreadLimitClause =
5026 D.getSingleClause<OMPThreadLimitClause>()) {
5027 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5028 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5029 /*IgnoreResultAssign*/ true);
5030 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5031 /*IsSigned=*/true);
5032 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005033
5034 if (const auto *NumThreadsClause =
5035 D.getSingleClause<OMPNumThreadsClause>()) {
5036 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5037 llvm::Value *NumThreads =
5038 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5039 /*IgnoreResultAssign*/ true);
5040 NumThreadsVal =
5041 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5042 }
5043
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005044 // Select the lesser of thread_limit and num_threads.
5045 if (NumThreadsVal)
5046 ThreadLimitVal = ThreadLimitVal
5047 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5048 ThreadLimitVal),
5049 NumThreadsVal, ThreadLimitVal)
5050 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005051
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005052 // Set default value passed to the runtime if either teams or a target
5053 // parallel type directive is found but no clause is specified.
5054 if (!ThreadLimitVal)
5055 ThreadLimitVal = DefaultThreadLimitVal;
5056
5057 return ThreadLimitVal;
5058 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005059
Samuel Antaob68e2db2016-03-03 16:20:23 +00005060 // If the current target region has a teams region enclosed, we need to get
5061 // the thread limit to pass to the runtime function call. This is done
5062 // by generating the expression in a inlined region. This is required because
5063 // the expression is captured in the enclosing target environment when the
5064 // teams directive is not combined with target.
5065
5066 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5067
5068 // FIXME: Accommodate other combined directives with teams when they become
5069 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005070 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5071 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005072 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5073 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5074 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5075 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5076 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5077 /*IsSigned=*/true);
5078 }
5079
5080 // If we have an enclosed teams directive but no thread_limit clause we use
5081 // the default value 0.
5082 return CGF.Builder.getInt32(0);
5083 }
5084
5085 // No teams associated with the directive.
5086 return nullptr;
5087}
5088
Samuel Antao86ace552016-04-27 22:40:57 +00005089namespace {
5090// \brief Utility to handle information from clauses associated with a given
5091// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5092// It provides a convenient interface to obtain the information and generate
5093// code for that information.
5094class MappableExprsHandler {
5095public:
5096 /// \brief Values for bit flags used to specify the mapping type for
5097 /// offloading.
5098 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005099 /// \brief Allocate memory on the device and move data from host to device.
5100 OMP_MAP_TO = 0x01,
5101 /// \brief Allocate memory on the device and move data from device to host.
5102 OMP_MAP_FROM = 0x02,
5103 /// \brief Always perform the requested mapping action on the element, even
5104 /// if it was already mapped before.
5105 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005106 /// \brief Delete the element from the device environment, ignoring the
5107 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005108 OMP_MAP_DELETE = 0x08,
5109 /// \brief The element being mapped is a pointer, therefore the pointee
5110 /// should be mapped as well.
5111 OMP_MAP_IS_PTR = 0x10,
5112 /// \brief This flags signals that an argument is the first one relating to
5113 /// a map/private clause expression. For some cases a single
5114 /// map/privatization results in multiple arguments passed to the runtime
5115 /// library.
5116 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005117 /// \brief Signal that the runtime library has to return the device pointer
5118 /// in the current position for the data being mapped.
5119 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005120 /// \brief This flag signals that the reference being passed is a pointer to
5121 /// private data.
5122 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005123 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005124 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005125 };
5126
Samuel Antaocc10b852016-07-28 14:23:26 +00005127 /// Class that associates information with a base pointer to be passed to the
5128 /// runtime library.
5129 class BasePointerInfo {
5130 /// The base pointer.
5131 llvm::Value *Ptr = nullptr;
5132 /// The base declaration that refers to this device pointer, or null if
5133 /// there is none.
5134 const ValueDecl *DevPtrDecl = nullptr;
5135
5136 public:
5137 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5138 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5139 llvm::Value *operator*() const { return Ptr; }
5140 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5141 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5142 };
5143
5144 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005145 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5146 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5147
5148private:
5149 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005150 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005151
5152 /// \brief Function the directive is being generated for.
5153 CodeGenFunction &CGF;
5154
Samuel Antaod486f842016-05-26 16:53:38 +00005155 /// \brief Set of all first private variables in the current directive.
5156 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5157
Samuel Antao6890b092016-07-28 14:25:09 +00005158 /// Map between device pointer declarations and their expression components.
5159 /// The key value for declarations in 'this' is null.
5160 llvm::DenseMap<
5161 const ValueDecl *,
5162 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5163 DevPointersMap;
5164
Samuel Antao86ace552016-04-27 22:40:57 +00005165 llvm::Value *getExprTypeSize(const Expr *E) const {
5166 auto ExprTy = E->getType().getCanonicalType();
5167
5168 // Reference types are ignored for mapping purposes.
5169 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5170 ExprTy = RefTy->getPointeeType().getCanonicalType();
5171
5172 // Given that an array section is considered a built-in type, we need to
5173 // do the calculation based on the length of the section instead of relying
5174 // on CGF.getTypeSize(E->getType()).
5175 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5176 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5177 OAE->getBase()->IgnoreParenImpCasts())
5178 .getCanonicalType();
5179
5180 // If there is no length associated with the expression, that means we
5181 // are using the whole length of the base.
5182 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5183 return CGF.getTypeSize(BaseTy);
5184
5185 llvm::Value *ElemSize;
5186 if (auto *PTy = BaseTy->getAs<PointerType>())
5187 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5188 else {
5189 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5190 assert(ATy && "Expecting array type if not a pointer type.");
5191 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5192 }
5193
5194 // If we don't have a length at this point, that is because we have an
5195 // array section with a single element.
5196 if (!OAE->getLength())
5197 return ElemSize;
5198
5199 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5200 LengthVal =
5201 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5202 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5203 }
5204 return CGF.getTypeSize(ExprTy);
5205 }
5206
5207 /// \brief Return the corresponding bits for a given map clause modifier. Add
5208 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00005209 /// map as the first one of a series of maps that relate to the same map
5210 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00005211 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5212 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00005213 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00005214 unsigned Bits = 0u;
5215 switch (MapType) {
5216 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00005217 case OMPC_MAP_release:
5218 // alloc and release is the default behavior in the runtime library, i.e.
5219 // if we don't pass any bits alloc/release that is what the runtime is
5220 // going to do. Therefore, we don't need to signal anything for these two
5221 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00005222 break;
5223 case OMPC_MAP_to:
5224 Bits = OMP_MAP_TO;
5225 break;
5226 case OMPC_MAP_from:
5227 Bits = OMP_MAP_FROM;
5228 break;
5229 case OMPC_MAP_tofrom:
5230 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5231 break;
5232 case OMPC_MAP_delete:
5233 Bits = OMP_MAP_DELETE;
5234 break;
Samuel Antao86ace552016-04-27 22:40:57 +00005235 default:
5236 llvm_unreachable("Unexpected map type!");
5237 break;
5238 }
5239 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00005240 Bits |= OMP_MAP_IS_PTR;
5241 if (AddIsFirstFlag)
5242 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00005243 if (MapTypeModifier == OMPC_MAP_always)
5244 Bits |= OMP_MAP_ALWAYS;
5245 return Bits;
5246 }
5247
5248 /// \brief Return true if the provided expression is a final array section. A
5249 /// final array section, is one whose length can't be proved to be one.
5250 bool isFinalArraySectionExpression(const Expr *E) const {
5251 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5252
5253 // It is not an array section and therefore not a unity-size one.
5254 if (!OASE)
5255 return false;
5256
5257 // An array section with no colon always refer to a single element.
5258 if (OASE->getColonLoc().isInvalid())
5259 return false;
5260
5261 auto *Length = OASE->getLength();
5262
5263 // If we don't have a length we have to check if the array has size 1
5264 // for this dimension. Also, we should always expect a length if the
5265 // base type is pointer.
5266 if (!Length) {
5267 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5268 OASE->getBase()->IgnoreParenImpCasts())
5269 .getCanonicalType();
5270 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5271 return ATy->getSize().getSExtValue() != 1;
5272 // If we don't have a constant dimension length, we have to consider
5273 // the current section as having any size, so it is not necessarily
5274 // unitary. If it happen to be unity size, that's user fault.
5275 return true;
5276 }
5277
5278 // Check if the length evaluates to 1.
5279 llvm::APSInt ConstLength;
5280 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5281 return true; // Can have more that size 1.
5282
5283 return ConstLength.getSExtValue() != 1;
5284 }
5285
5286 /// \brief Generate the base pointers, section pointers, sizes and map type
5287 /// bits for the provided map type, map modifier, and expression components.
5288 /// \a IsFirstComponent should be set to true if the provided set of
5289 /// components is the first associated with a capture.
5290 void generateInfoForComponentList(
5291 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5292 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00005293 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005294 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5295 bool IsFirstComponentList) const {
5296
5297 // The following summarizes what has to be generated for each map and the
5298 // types bellow. The generated information is expressed in this order:
5299 // base pointer, section pointer, size, flags
5300 // (to add to the ones that come from the map type and modifier).
5301 //
5302 // double d;
5303 // int i[100];
5304 // float *p;
5305 //
5306 // struct S1 {
5307 // int i;
5308 // float f[50];
5309 // }
5310 // struct S2 {
5311 // int i;
5312 // float f[50];
5313 // S1 s;
5314 // double *p;
5315 // struct S2 *ps;
5316 // }
5317 // S2 s;
5318 // S2 *ps;
5319 //
5320 // map(d)
5321 // &d, &d, sizeof(double), noflags
5322 //
5323 // map(i)
5324 // &i, &i, 100*sizeof(int), noflags
5325 //
5326 // map(i[1:23])
5327 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5328 //
5329 // map(p)
5330 // &p, &p, sizeof(float*), noflags
5331 //
5332 // map(p[1:24])
5333 // p, &p[1], 24*sizeof(float), noflags
5334 //
5335 // map(s)
5336 // &s, &s, sizeof(S2), noflags
5337 //
5338 // map(s.i)
5339 // &s, &(s.i), sizeof(int), noflags
5340 //
5341 // map(s.s.f)
5342 // &s, &(s.i.f), 50*sizeof(int), noflags
5343 //
5344 // map(s.p)
5345 // &s, &(s.p), sizeof(double*), noflags
5346 //
5347 // map(s.p[:22], s.a s.b)
5348 // &s, &(s.p), sizeof(double*), noflags
5349 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5350 //
5351 // map(s.ps)
5352 // &s, &(s.ps), sizeof(S2*), noflags
5353 //
5354 // map(s.ps->s.i)
5355 // &s, &(s.ps), sizeof(S2*), noflags
5356 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5357 //
5358 // map(s.ps->ps)
5359 // &s, &(s.ps), sizeof(S2*), noflags
5360 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5361 //
5362 // map(s.ps->ps->ps)
5363 // &s, &(s.ps), sizeof(S2*), noflags
5364 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5365 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5366 //
5367 // map(s.ps->ps->s.f[:22])
5368 // &s, &(s.ps), sizeof(S2*), noflags
5369 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5370 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5371 //
5372 // map(ps)
5373 // &ps, &ps, sizeof(S2*), noflags
5374 //
5375 // map(ps->i)
5376 // ps, &(ps->i), sizeof(int), noflags
5377 //
5378 // map(ps->s.f)
5379 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5380 //
5381 // map(ps->p)
5382 // ps, &(ps->p), sizeof(double*), noflags
5383 //
5384 // map(ps->p[:22])
5385 // ps, &(ps->p), sizeof(double*), noflags
5386 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5387 //
5388 // map(ps->ps)
5389 // ps, &(ps->ps), sizeof(S2*), noflags
5390 //
5391 // map(ps->ps->s.i)
5392 // ps, &(ps->ps), sizeof(S2*), noflags
5393 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5394 //
5395 // map(ps->ps->ps)
5396 // ps, &(ps->ps), sizeof(S2*), noflags
5397 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5398 //
5399 // map(ps->ps->ps->ps)
5400 // ps, &(ps->ps), sizeof(S2*), noflags
5401 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5402 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5403 //
5404 // map(ps->ps->ps->s.f[:22])
5405 // ps, &(ps->ps), sizeof(S2*), noflags
5406 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5407 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5408 // extra_flag
5409
5410 // Track if the map information being generated is the first for a capture.
5411 bool IsCaptureFirstInfo = IsFirstComponentList;
5412
5413 // Scan the components from the base to the complete expression.
5414 auto CI = Components.rbegin();
5415 auto CE = Components.rend();
5416 auto I = CI;
5417
5418 // Track if the map information being generated is the first for a list of
5419 // components.
5420 bool IsExpressionFirstInfo = true;
5421 llvm::Value *BP = nullptr;
5422
5423 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5424 // The base is the 'this' pointer. The content of the pointer is going
5425 // to be the base of the field being mapped.
5426 BP = CGF.EmitScalarExpr(ME->getBase());
5427 } else {
5428 // The base is the reference to the variable.
5429 // BP = &Var.
5430 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5431 .getPointer();
5432
5433 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00005434 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00005435 // reference. References are ignored for mapping purposes.
5436 QualType Ty =
5437 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5438 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5439 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00005440 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00005441 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00005442 .getPointer();
5443
5444 // We do not need to generate individual map information for the
5445 // pointer, it can be associated with the combined storage.
5446 ++I;
5447 }
5448 }
5449
5450 for (; I != CE; ++I) {
5451 auto Next = std::next(I);
5452
5453 // We need to generate the addresses and sizes if this is the last
5454 // component, if the component is a pointer or if it is an array section
5455 // whose length can't be proved to be one. If this is a pointer, it
5456 // becomes the base address for the following components.
5457
5458 // A final array section, is one whose length can't be proved to be one.
5459 bool IsFinalArraySection =
5460 isFinalArraySectionExpression(I->getAssociatedExpression());
5461
5462 // Get information on whether the element is a pointer. Have to do a
5463 // special treatment for array sections given that they are built-in
5464 // types.
5465 const auto *OASE =
5466 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5467 bool IsPointer =
5468 (OASE &&
5469 OMPArraySectionExpr::getBaseOriginalType(OASE)
5470 .getCanonicalType()
5471 ->isAnyPointerType()) ||
5472 I->getAssociatedExpression()->getType()->isAnyPointerType();
5473
5474 if (Next == CE || IsPointer || IsFinalArraySection) {
5475
5476 // If this is not the last component, we expect the pointer to be
5477 // associated with an array expression or member expression.
5478 assert((Next == CE ||
5479 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5480 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5481 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5482 "Unexpected expression");
5483
Samuel Antao86ace552016-04-27 22:40:57 +00005484 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5485 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5486
Samuel Antao03a3cec2016-07-27 22:52:16 +00005487 // If we have a member expression and the current component is a
5488 // reference, we have to map the reference too. Whenever we have a
5489 // reference, the section that reference refers to is going to be a
5490 // load instruction from the storage assigned to the reference.
5491 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5492 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5493 auto *LI = cast<llvm::LoadInst>(LB);
5494 auto *RefAddr = LI->getPointerOperand();
5495
5496 BasePointers.push_back(BP);
5497 Pointers.push_back(RefAddr);
5498 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5499 Types.push_back(getMapTypeBits(
5500 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5501 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5502 IsExpressionFirstInfo = false;
5503 IsCaptureFirstInfo = false;
5504 // The reference will be the next base address.
5505 BP = RefAddr;
5506 }
5507
5508 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00005509 Pointers.push_back(LB);
5510 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00005511
Samuel Antao6782e942016-05-26 16:48:10 +00005512 // We need to add a pointer flag for each map that comes from the
5513 // same expression except for the first one. We also need to signal
5514 // this map is the first one that relates with the current capture
5515 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00005516 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5517 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00005518 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00005519
5520 // If we have a final array section, we are done with this expression.
5521 if (IsFinalArraySection)
5522 break;
5523
5524 // The pointer becomes the base for the next element.
5525 if (Next != CE)
5526 BP = LB;
5527
5528 IsExpressionFirstInfo = false;
5529 IsCaptureFirstInfo = false;
5530 continue;
5531 }
5532 }
5533 }
5534
Samuel Antaod486f842016-05-26 16:53:38 +00005535 /// \brief Return the adjusted map modifiers if the declaration a capture
5536 /// refers to appears in a first-private clause. This is expected to be used
5537 /// only with directives that start with 'target'.
5538 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5539 unsigned CurrentModifiers) {
5540 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5541
5542 // A first private variable captured by reference will use only the
5543 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5544 // declaration is known as first-private in this handler.
5545 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5546 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5547 MappableExprsHandler::OMP_MAP_TO;
5548
5549 // We didn't modify anything.
5550 return CurrentModifiers;
5551 }
5552
Samuel Antao86ace552016-04-27 22:40:57 +00005553public:
5554 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00005555 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00005556 // Extract firstprivate clause information.
5557 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5558 for (const auto *D : C->varlists())
5559 FirstPrivateDecls.insert(
5560 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00005561 // Extract device pointer clause information.
5562 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5563 for (auto L : C->component_lists())
5564 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00005565 }
Samuel Antao86ace552016-04-27 22:40:57 +00005566
5567 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00005568 /// types for the extracted mappable expressions. Also, for each item that
5569 /// relates with a device pointer, a pair of the relevant declaration and
5570 /// index where it occurs is appended to the device pointers info array.
5571 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005572 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5573 MapFlagsArrayTy &Types) const {
5574 BasePointers.clear();
5575 Pointers.clear();
5576 Sizes.clear();
5577 Types.clear();
5578
5579 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00005580 /// Kind that defines how a device pointer has to be returned.
5581 enum ReturnPointerKind {
5582 // Don't have to return any pointer.
5583 RPK_None,
5584 // Pointer is the base of the declaration.
5585 RPK_Base,
5586 // Pointer is a member of the base declaration - 'this'
5587 RPK_Member,
5588 // Pointer is a reference and a member of the base declaration - 'this'
5589 RPK_MemberReference,
5590 };
Samuel Antao86ace552016-04-27 22:40:57 +00005591 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00005592 OpenMPMapClauseKind MapType;
5593 OpenMPMapClauseKind MapTypeModifier;
5594 ReturnPointerKind ReturnDevicePointer;
5595
5596 MapInfo()
5597 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5598 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00005599 MapInfo(
5600 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5601 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5602 ReturnPointerKind ReturnDevicePointer)
5603 : Components(Components), MapType(MapType),
5604 MapTypeModifier(MapTypeModifier),
5605 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00005606 };
5607
5608 // We have to process the component lists that relate with the same
5609 // declaration in a single chunk so that we can generate the map flags
5610 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00005611 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00005612
5613 // Helper function to fill the information map for the different supported
5614 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00005615 auto &&InfoGen = [&Info](
5616 const ValueDecl *D,
5617 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5618 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005619 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005620 const ValueDecl *VD =
5621 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5622 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5623 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00005624
Paul Robinson78fb1322016-08-01 22:12:46 +00005625 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005626 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005627 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005628 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5629 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005630 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005631 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005632 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5633 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005634 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005635 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005636 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5637 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00005638
Samuel Antaocc10b852016-07-28 14:23:26 +00005639 // Look at the use_device_ptr clause information and mark the existing map
5640 // entries as such. If there is no map information for an entry in the
5641 // use_device_ptr list, we create one with map type 'alloc' and zero size
5642 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00005643 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005644 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00005645 for (auto L : C->component_lists()) {
5646 assert(!L.second.empty() && "Not expecting empty list of components!");
5647 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5648 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5649 auto *IE = L.second.back().getAssociatedExpression();
5650 // If the first component is a member expression, we have to look into
5651 // 'this', which maps to null in the map of map information. Otherwise
5652 // look directly for the information.
5653 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5654
5655 // We potentially have map information for this declaration already.
5656 // Look for the first set of components that refer to it.
5657 if (It != Info.end()) {
5658 auto CI = std::find_if(
5659 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5660 return MI.Components.back().getAssociatedDeclaration() == VD;
5661 });
5662 // If we found a map entry, signal that the pointer has to be returned
5663 // and move on to the next declaration.
5664 if (CI != It->second.end()) {
5665 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5666 ? (VD->getType()->isReferenceType()
5667 ? MapInfo::RPK_MemberReference
5668 : MapInfo::RPK_Member)
5669 : MapInfo::RPK_Base;
5670 continue;
5671 }
5672 }
5673
5674 // We didn't find any match in our map information - generate a zero
5675 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00005676 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00005677 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00005678 this->CGF
5679 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00005680 .getScalarVal();
5681 BasePointers.push_back({Ptr, VD});
5682 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00005683 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00005684 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5685 }
5686
Samuel Antao86ace552016-04-27 22:40:57 +00005687 for (auto &M : Info) {
5688 // We need to know when we generate information for the first component
5689 // associated with a capture, because the mapping flags depend on it.
5690 bool IsFirstComponentList = true;
5691 for (MapInfo &L : M.second) {
5692 assert(!L.Components.empty() &&
5693 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00005694
5695 // Remember the current base pointer index.
5696 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00005697 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00005698 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5699 L.Components, BasePointers, Pointers,
5700 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00005701
5702 // If this entry relates with a device pointer, set the relevant
5703 // declaration and add the 'return pointer' flag.
5704 if (IsFirstComponentList &&
5705 L.ReturnDevicePointer != MapInfo::RPK_None) {
5706 // If the pointer is not the base of the map, we need to skip the
5707 // base. If it is a reference in a member field, we also need to skip
5708 // the map of the reference.
5709 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5710 ++CurrentBasePointersIdx;
5711 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5712 ++CurrentBasePointersIdx;
5713 }
5714 assert(BasePointers.size() > CurrentBasePointersIdx &&
5715 "Unexpected number of mapped base pointers.");
5716
5717 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5718 assert(RelevantVD &&
5719 "No relevant declaration related with device pointer??");
5720
5721 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5722 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5723 }
Samuel Antao86ace552016-04-27 22:40:57 +00005724 IsFirstComponentList = false;
5725 }
5726 }
5727 }
5728
5729 /// \brief Generate the base pointers, section pointers, sizes and map types
5730 /// associated to a given capture.
5731 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00005732 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005733 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005734 MapValuesArrayTy &Pointers,
5735 MapValuesArrayTy &Sizes,
5736 MapFlagsArrayTy &Types) const {
5737 assert(!Cap->capturesVariableArrayType() &&
5738 "Not expecting to generate map info for a variable array type!");
5739
5740 BasePointers.clear();
5741 Pointers.clear();
5742 Sizes.clear();
5743 Types.clear();
5744
Samuel Antao6890b092016-07-28 14:25:09 +00005745 // We need to know when we generating information for the first component
5746 // associated with a capture, because the mapping flags depend on it.
5747 bool IsFirstComponentList = true;
5748
Samuel Antao86ace552016-04-27 22:40:57 +00005749 const ValueDecl *VD =
5750 Cap->capturesThis()
5751 ? nullptr
5752 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5753
Samuel Antao6890b092016-07-28 14:25:09 +00005754 // If this declaration appears in a is_device_ptr clause we just have to
5755 // pass the pointer by value. If it is a reference to a declaration, we just
5756 // pass its value, otherwise, if it is a member expression, we need to map
5757 // 'to' the field.
5758 if (!VD) {
5759 auto It = DevPointersMap.find(VD);
5760 if (It != DevPointersMap.end()) {
5761 for (auto L : It->second) {
5762 generateInfoForComponentList(
5763 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5764 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5765 IsFirstComponentList = false;
5766 }
5767 return;
5768 }
5769 } else if (DevPointersMap.count(VD)) {
5770 BasePointers.push_back({Arg, VD});
5771 Pointers.push_back(Arg);
5772 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5773 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5774 return;
5775 }
5776
Paul Robinson78fb1322016-08-01 22:12:46 +00005777 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005778 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00005779 for (auto L : C->decl_component_lists(VD)) {
5780 assert(L.first == VD &&
5781 "We got information for the wrong declaration??");
5782 assert(!L.second.empty() &&
5783 "Not expecting declaration with no component lists.");
5784 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5785 L.second, BasePointers, Pointers, Sizes,
5786 Types, IsFirstComponentList);
5787 IsFirstComponentList = false;
5788 }
5789
5790 return;
5791 }
Samuel Antaod486f842016-05-26 16:53:38 +00005792
5793 /// \brief Generate the default map information for a given capture \a CI,
5794 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00005795 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5796 const FieldDecl &RI, llvm::Value *CV,
5797 MapBaseValuesArrayTy &CurBasePointers,
5798 MapValuesArrayTy &CurPointers,
5799 MapValuesArrayTy &CurSizes,
5800 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00005801
5802 // Do the default mapping.
5803 if (CI.capturesThis()) {
5804 CurBasePointers.push_back(CV);
5805 CurPointers.push_back(CV);
5806 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5807 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5808 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00005809 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00005810 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005811 CurBasePointers.push_back(CV);
5812 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00005813 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005814 // We have to signal to the runtime captures passed by value that are
5815 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00005816 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00005817 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5818 } else {
5819 // Pointers are implicitly mapped with a zero size and no flags
5820 // (other than first map that is added for all implicit maps).
5821 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00005822 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5823 }
5824 } else {
5825 assert(CI.capturesVariable() && "Expected captured reference.");
5826 CurBasePointers.push_back(CV);
5827 CurPointers.push_back(CV);
5828
5829 const ReferenceType *PtrTy =
5830 cast<ReferenceType>(RI.getType().getTypePtr());
5831 QualType ElementType = PtrTy->getPointeeType();
5832 CurSizes.push_back(CGF.getTypeSize(ElementType));
5833 // The default map type for a scalar/complex type is 'to' because by
5834 // default the value doesn't have to be retrieved. For an aggregate
5835 // type, the default is 'tofrom'.
5836 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00005837 ? (OMP_MAP_TO | OMP_MAP_FROM)
5838 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00005839
5840 // If we have a capture by reference we may need to add the private
5841 // pointer flag if the base declaration shows in some first-private
5842 // clause.
5843 CurMapTypes.back() =
5844 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5845 }
5846 // Every default map produces a single argument, so, it is always the
5847 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00005848 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00005849 }
Samuel Antao86ace552016-04-27 22:40:57 +00005850};
Samuel Antaodf158d52016-04-27 22:58:19 +00005851
5852enum OpenMPOffloadingReservedDeviceIDs {
5853 /// \brief Device ID if the device was not defined, runtime should get it
5854 /// from environment variables in the spec.
5855 OMP_DEVICEID_UNDEF = -1,
5856};
5857} // anonymous namespace
5858
5859/// \brief Emit the arrays used to pass the captures and map information to the
5860/// offloading runtime library. If there is no map or capture information,
5861/// return nullptr by reference.
5862static void
Samuel Antaocc10b852016-07-28 14:23:26 +00005863emitOffloadingArrays(CodeGenFunction &CGF,
5864 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00005865 MappableExprsHandler::MapValuesArrayTy &Pointers,
5866 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00005867 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5868 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005869 auto &CGM = CGF.CGM;
5870 auto &Ctx = CGF.getContext();
5871
Samuel Antaocc10b852016-07-28 14:23:26 +00005872 // Reset the array information.
5873 Info.clearArrayInfo();
5874 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00005875
Samuel Antaocc10b852016-07-28 14:23:26 +00005876 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005877 // Detect if we have any capture size requiring runtime evaluation of the
5878 // size so that a constant array could be eventually used.
5879 bool hasRuntimeEvaluationCaptureSize = false;
5880 for (auto *S : Sizes)
5881 if (!isa<llvm::Constant>(S)) {
5882 hasRuntimeEvaluationCaptureSize = true;
5883 break;
5884 }
5885
Samuel Antaocc10b852016-07-28 14:23:26 +00005886 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00005887 QualType PointerArrayType =
5888 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5889 /*IndexTypeQuals=*/0);
5890
Samuel Antaocc10b852016-07-28 14:23:26 +00005891 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005892 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00005893 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005894 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5895
5896 // If we don't have any VLA types or other types that require runtime
5897 // evaluation, we can use a constant array for the map sizes, otherwise we
5898 // need to fill up the arrays as we do for the pointers.
5899 if (hasRuntimeEvaluationCaptureSize) {
5900 QualType SizeArrayType = Ctx.getConstantArrayType(
5901 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5902 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00005903 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005904 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5905 } else {
5906 // We expect all the sizes to be constant, so we collect them to create
5907 // a constant array.
5908 SmallVector<llvm::Constant *, 16> ConstSizes;
5909 for (auto S : Sizes)
5910 ConstSizes.push_back(cast<llvm::Constant>(S));
5911
5912 auto *SizesArrayInit = llvm::ConstantArray::get(
5913 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5914 auto *SizesArrayGbl = new llvm::GlobalVariable(
5915 CGM.getModule(), SizesArrayInit->getType(),
5916 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5917 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005918 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005919 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005920 }
5921
5922 // The map types are always constant so we don't need to generate code to
5923 // fill arrays. Instead, we create an array constant.
5924 llvm::Constant *MapTypesArrayInit =
5925 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5926 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5927 CGM.getModule(), MapTypesArrayInit->getType(),
5928 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5929 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005930 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005931 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005932
Samuel Antaocc10b852016-07-28 14:23:26 +00005933 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5934 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00005935 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005936 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5937 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00005938 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5939 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00005940 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5941 CGF.Builder.CreateStore(BPVal, BPAddr);
5942
Samuel Antaocc10b852016-07-28 14:23:26 +00005943 if (Info.requiresDevicePointerInfo())
5944 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
5945 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
5946
Samuel Antaodf158d52016-04-27 22:58:19 +00005947 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00005948 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005949 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5950 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00005951 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5952 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00005953 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5954 CGF.Builder.CreateStore(PVal, PAddr);
5955
5956 if (hasRuntimeEvaluationCaptureSize) {
5957 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005958 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5959 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005960 /*Idx0=*/0,
5961 /*Idx1=*/i);
5962 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5963 CGF.Builder.CreateStore(
5964 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5965 SAddr);
5966 }
5967 }
5968 }
5969}
5970/// \brief Emit the arguments to be passed to the runtime library based on the
5971/// arrays of pointers, sizes and map types.
5972static void emitOffloadingArraysArgument(
5973 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5974 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005975 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005976 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00005977 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005978 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005979 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5980 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005981 /*Idx0=*/0, /*Idx1=*/0);
5982 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005983 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5984 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005985 /*Idx0=*/0,
5986 /*Idx1=*/0);
5987 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005988 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005989 /*Idx0=*/0, /*Idx1=*/0);
5990 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005991 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
5992 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005993 /*Idx0=*/0,
5994 /*Idx1=*/0);
5995 } else {
5996 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5997 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5998 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5999 MapTypesArrayArg =
6000 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6001 }
Samuel Antao86ace552016-04-27 22:40:57 +00006002}
6003
Samuel Antaobed3c462015-10-02 16:14:20 +00006004void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6005 const OMPExecutableDirective &D,
6006 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006007 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006008 const Expr *IfCond, const Expr *Device,
6009 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006010 if (!CGF.HaveInsertPoint())
6011 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006012
Samuel Antaoee8fb302016-01-06 13:42:12 +00006013 assert(OutlinedFn && "Invalid outlined function!");
6014
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006015 auto &Ctx = CGF.getContext();
6016
Samuel Antao86ace552016-04-27 22:40:57 +00006017 // Fill up the arrays with all the captured variables.
6018 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006019 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006020 MappableExprsHandler::MapValuesArrayTy Pointers;
6021 MappableExprsHandler::MapValuesArrayTy Sizes;
6022 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006023
Samuel Antaocc10b852016-07-28 14:23:26 +00006024 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006025 MappableExprsHandler::MapValuesArrayTy CurPointers;
6026 MappableExprsHandler::MapValuesArrayTy CurSizes;
6027 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6028
Samuel Antaod486f842016-05-26 16:53:38 +00006029 // Get mappable expression information.
6030 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006031
6032 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6033 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006034 auto CV = CapturedVars.begin();
6035 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6036 CE = CS.capture_end();
6037 CI != CE; ++CI, ++RI, ++CV) {
6038 StringRef Name;
6039 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00006040
Samuel Antao86ace552016-04-27 22:40:57 +00006041 CurBasePointers.clear();
6042 CurPointers.clear();
6043 CurSizes.clear();
6044 CurMapTypes.clear();
6045
6046 // VLA sizes are passed to the outlined region by copy and do not have map
6047 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006048 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006049 CurBasePointers.push_back(*CV);
6050 CurPointers.push_back(*CV);
6051 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006052 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006053 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6054 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006055 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006056 // If we have any information in the map clause, we use it, otherwise we
6057 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006058 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006059 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006060 if (CurBasePointers.empty())
6061 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6062 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006063 }
Samuel Antao86ace552016-04-27 22:40:57 +00006064 // We expect to have at least an element of information for this capture.
6065 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6066 assert(CurBasePointers.size() == CurPointers.size() &&
6067 CurBasePointers.size() == CurSizes.size() &&
6068 CurBasePointers.size() == CurMapTypes.size() &&
6069 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006070
Samuel Antao86ace552016-04-27 22:40:57 +00006071 // The kernel args are always the first elements of the base pointers
6072 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006073 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006074 // We need to append the results of this capture to what we already have.
6075 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6076 Pointers.append(CurPointers.begin(), CurPointers.end());
6077 Sizes.append(CurSizes.begin(), CurSizes.end());
6078 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006079 }
6080
6081 // Keep track on whether the host function has to be executed.
6082 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006083 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006084 auto OffloadError = CGF.MakeAddrLValue(
6085 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6086 OffloadErrorQType);
6087 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6088 OffloadError);
6089
6090 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006091 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6092 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006093 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6094 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006095 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006096 TargetDataInfo Info;
6097 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6098 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6099 Info.PointersArray, Info.SizesArray,
6100 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006101
6102 // On top of the arrays that were filled up, the target offloading call
6103 // takes as arguments the device id as well as the host pointer. The host
6104 // pointer is used by the runtime library to identify the current target
6105 // region, so it only has to be unique and not necessarily point to
6106 // anything. It could be the pointer to the outlined function that
6107 // implements the target region, but we aren't using that so that the
6108 // compiler doesn't need to keep that, and could therefore inline the host
6109 // function if proven worthwhile during optimization.
6110
Samuel Antaoee8fb302016-01-06 13:42:12 +00006111 // From this point on, we need to have an ID of the target region defined.
6112 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006113
6114 // Emit device ID if any.
6115 llvm::Value *DeviceID;
6116 if (Device)
6117 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006118 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006119 else
6120 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6121
Samuel Antaodf158d52016-04-27 22:58:19 +00006122 // Emit the number of elements in the offloading arrays.
6123 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6124
Samuel Antaob68e2db2016-03-03 16:20:23 +00006125 // Return value of the runtime offloading call.
6126 llvm::Value *Return;
6127
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006128 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6129 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006130
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006131 // The target region is an outlined function launched by the runtime
6132 // via calls __tgt_target() or __tgt_target_teams().
6133 //
6134 // __tgt_target() launches a target region with one team and one thread,
6135 // executing a serial region. This master thread may in turn launch
6136 // more threads within its team upon encountering a parallel region,
6137 // however, no additional teams can be launched on the device.
6138 //
6139 // __tgt_target_teams() launches a target region with one or more teams,
6140 // each with one or more threads. This call is required for target
6141 // constructs such as:
6142 // 'target teams'
6143 // 'target' / 'teams'
6144 // 'target teams distribute parallel for'
6145 // 'target parallel'
6146 // and so on.
6147 //
6148 // Note that on the host and CPU targets, the runtime implementation of
6149 // these calls simply call the outlined function without forking threads.
6150 // The outlined functions themselves have runtime calls to
6151 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
6152 // the compiler in emitTeamsCall() and emitParallelCall().
6153 //
6154 // In contrast, on the NVPTX target, the implementation of
6155 // __tgt_target_teams() launches a GPU kernel with the requested number
6156 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006157 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006158 // If we have NumTeams defined this means that we have an enclosed teams
6159 // region. Therefore we also expect to have NumThreads defined. These two
6160 // values should be defined in the presence of a teams directive,
6161 // regardless of having any clauses associated. If the user is using teams
6162 // but no clauses, these two values will be the default that should be
6163 // passed to the runtime library - a 32-bit integer with the value zero.
6164 assert(NumThreads && "Thread limit expression should be available along "
6165 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00006166 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006167 DeviceID, OutlinedFnID,
6168 PointerNum, Info.BasePointersArray,
6169 Info.PointersArray, Info.SizesArray,
6170 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006171 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00006172 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006173 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006174 } else {
6175 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006176 DeviceID, OutlinedFnID,
6177 PointerNum, Info.BasePointersArray,
6178 Info.PointersArray, Info.SizesArray,
6179 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006180 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00006181 OffloadingArgs);
6182 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006183
6184 CGF.EmitStoreOfScalar(Return, OffloadError);
6185 };
6186
Samuel Antaoee8fb302016-01-06 13:42:12 +00006187 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006188 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6189 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00006190 OffloadError);
6191 };
6192
6193 // If we have a target function ID it means that we need to support
6194 // offloading, otherwise, just execute on the host. We need to execute on host
6195 // regardless of the conditional in the if clause if, e.g., the user do not
6196 // specify target triples.
6197 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006198 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00006199 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006200 else {
6201 RegionCodeGenTy ThenRCG(ThenGen);
6202 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006203 }
6204 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006205 RegionCodeGenTy ElseRCG(ElseGen);
6206 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006207 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006208
6209 // Check the error code and execute the host version if required.
6210 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6211 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6212 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6213 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6214 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6215
6216 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00006217 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00006218 CGF.EmitBranch(OffloadContBlock);
6219
6220 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006221}
Samuel Antaoee8fb302016-01-06 13:42:12 +00006222
6223void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6224 StringRef ParentName) {
6225 if (!S)
6226 return;
6227
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006228 // Codegen OMP target directives that offload compute to the device.
6229 bool requiresDeviceCodegen =
6230 isa<OMPExecutableDirective>(S) &&
6231 isOpenMPTargetExecutionDirective(
6232 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00006233
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006234 if (requiresDeviceCodegen) {
6235 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006236 unsigned DeviceID;
6237 unsigned FileID;
6238 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006239 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006240 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006241
6242 // Is this a target region that should not be emitted as an entry point? If
6243 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00006244 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6245 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00006246 return;
6247
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006248 switch (S->getStmtClass()) {
6249 case Stmt::OMPTargetDirectiveClass:
6250 CodeGenFunction::EmitOMPTargetDeviceFunction(
6251 CGM, ParentName, cast<OMPTargetDirective>(*S));
6252 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00006253 case Stmt::OMPTargetParallelDirectiveClass:
6254 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
6255 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
6256 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006257 case Stmt::OMPTargetTeamsDirectiveClass:
6258 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
6259 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
6260 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006261 default:
6262 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
6263 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006264 return;
6265 }
6266
6267 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00006268 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00006269 return;
6270
6271 scanForTargetRegionsFunctions(
6272 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6273 ParentName);
6274 return;
6275 }
6276
6277 // If this is a lambda function, look into its body.
6278 if (auto *L = dyn_cast<LambdaExpr>(S))
6279 S = L->getBody();
6280
6281 // Keep looking for target regions recursively.
6282 for (auto *II : S->children())
6283 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006284}
6285
6286bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6287 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6288
6289 // If emitting code for the host, we do not process FD here. Instead we do
6290 // the normal code generation.
6291 if (!CGM.getLangOpts().OpenMPIsDevice)
6292 return false;
6293
6294 // Try to detect target regions in the function.
6295 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6296
Samuel Antao4b75b872016-12-12 19:26:31 +00006297 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00006298 // scanning. Therefore, we signal that this function is completely dealt
6299 // with.
6300 return true;
6301}
6302
6303bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6304 if (!CGM.getLangOpts().OpenMPIsDevice)
6305 return false;
6306
6307 // Check if there are Ctors/Dtors in this declaration and look for target
6308 // regions in it. We use the complete variant to produce the kernel name
6309 // mangling.
6310 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6311 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6312 for (auto *Ctor : RD->ctors()) {
6313 StringRef ParentName =
6314 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6315 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6316 }
6317 auto *Dtor = RD->getDestructor();
6318 if (Dtor) {
6319 StringRef ParentName =
6320 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6321 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6322 }
6323 }
6324
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00006325 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00006326 // implemented yet). Therefore we signal that GD was processed in this case.
6327 return true;
6328}
6329
6330bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6331 auto *VD = GD.getDecl();
6332 if (isa<FunctionDecl>(VD))
6333 return emitTargetFunctions(GD);
6334
6335 return emitTargetGlobalVariable(GD);
6336}
6337
6338llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6339 // If we have offloading in the current module, we need to emit the entries
6340 // now and register the offloading descriptor.
6341 createOffloadEntriesAndInfoMetadata();
6342
6343 // Create and register the offloading binary descriptors. This is the main
6344 // entity that captures all the information about offloading in the current
6345 // compilation unit.
6346 return createOffloadingBinaryDescriptorRegistration();
6347}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006348
6349void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6350 const OMPExecutableDirective &D,
6351 SourceLocation Loc,
6352 llvm::Value *OutlinedFn,
6353 ArrayRef<llvm::Value *> CapturedVars) {
6354 if (!CGF.HaveInsertPoint())
6355 return;
6356
6357 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6358 CodeGenFunction::RunCleanupsScope Scope(CGF);
6359
6360 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6361 llvm::Value *Args[] = {
6362 RTLoc,
6363 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6364 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6365 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6366 RealArgs.append(std::begin(Args), std::end(Args));
6367 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6368
6369 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6370 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6371}
6372
6373void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00006374 const Expr *NumTeams,
6375 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006376 SourceLocation Loc) {
6377 if (!CGF.HaveInsertPoint())
6378 return;
6379
6380 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6381
Carlo Bertollic6872252016-04-04 15:55:02 +00006382 llvm::Value *NumTeamsVal =
6383 (NumTeams)
6384 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6385 CGF.CGM.Int32Ty, /* isSigned = */ true)
6386 : CGF.Builder.getInt32(0);
6387
6388 llvm::Value *ThreadLimitVal =
6389 (ThreadLimit)
6390 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6391 CGF.CGM.Int32Ty, /* isSigned = */ true)
6392 : CGF.Builder.getInt32(0);
6393
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006394 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00006395 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6396 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006397 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6398 PushNumTeamsArgs);
6399}
Samuel Antaodf158d52016-04-27 22:58:19 +00006400
Samuel Antaocc10b852016-07-28 14:23:26 +00006401void CGOpenMPRuntime::emitTargetDataCalls(
6402 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6403 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006404 if (!CGF.HaveInsertPoint())
6405 return;
6406
Samuel Antaocc10b852016-07-28 14:23:26 +00006407 // Action used to replace the default codegen action and turn privatization
6408 // off.
6409 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00006410
6411 // Generate the code for the opening of the data environment. Capture all the
6412 // arguments of the runtime call by reference because they are used in the
6413 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006414 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
6415 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006416 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006417 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00006418 MappableExprsHandler::MapValuesArrayTy Pointers;
6419 MappableExprsHandler::MapValuesArrayTy Sizes;
6420 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6421
6422 // Get map clause information.
6423 MappableExprsHandler MCHandler(D, CGF);
6424 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00006425
6426 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006427 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006428
6429 llvm::Value *BasePointersArrayArg = nullptr;
6430 llvm::Value *PointersArrayArg = nullptr;
6431 llvm::Value *SizesArrayArg = nullptr;
6432 llvm::Value *MapTypesArrayArg = nullptr;
6433 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006434 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006435
6436 // Emit device ID if any.
6437 llvm::Value *DeviceID = nullptr;
6438 if (Device)
6439 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6440 CGF.Int32Ty, /*isSigned=*/true);
6441 else
6442 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6443
6444 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006445 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006446
6447 llvm::Value *OffloadingArgs[] = {
6448 DeviceID, PointerNum, BasePointersArrayArg,
6449 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6450 auto &RT = CGF.CGM.getOpenMPRuntime();
6451 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6452 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00006453
6454 // If device pointer privatization is required, emit the body of the region
6455 // here. It will have to be duplicated: with and without privatization.
6456 if (!Info.CaptureDeviceAddrMap.empty())
6457 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006458 };
6459
6460 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006461 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006462 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00006463
6464 llvm::Value *BasePointersArrayArg = nullptr;
6465 llvm::Value *PointersArrayArg = nullptr;
6466 llvm::Value *SizesArrayArg = nullptr;
6467 llvm::Value *MapTypesArrayArg = nullptr;
6468 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006469 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006470
6471 // Emit device ID if any.
6472 llvm::Value *DeviceID = nullptr;
6473 if (Device)
6474 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6475 CGF.Int32Ty, /*isSigned=*/true);
6476 else
6477 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6478
6479 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006480 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006481
6482 llvm::Value *OffloadingArgs[] = {
6483 DeviceID, PointerNum, BasePointersArrayArg,
6484 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6485 auto &RT = CGF.CGM.getOpenMPRuntime();
6486 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6487 OffloadingArgs);
6488 };
6489
Samuel Antaocc10b852016-07-28 14:23:26 +00006490 // If we need device pointer privatization, we need to emit the body of the
6491 // region with no privatization in the 'else' branch of the conditional.
6492 // Otherwise, we don't have to do anything.
6493 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6494 PrePostActionTy &) {
6495 if (!Info.CaptureDeviceAddrMap.empty()) {
6496 CodeGen.setAction(NoPrivAction);
6497 CodeGen(CGF);
6498 }
6499 };
6500
6501 // We don't have to do anything to close the region if the if clause evaluates
6502 // to false.
6503 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00006504
6505 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006506 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006507 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006508 RegionCodeGenTy RCG(BeginThenGen);
6509 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006510 }
6511
Samuel Antaocc10b852016-07-28 14:23:26 +00006512 // If we don't require privatization of device pointers, we emit the body in
6513 // between the runtime calls. This avoids duplicating the body code.
6514 if (Info.CaptureDeviceAddrMap.empty()) {
6515 CodeGen.setAction(NoPrivAction);
6516 CodeGen(CGF);
6517 }
Samuel Antaodf158d52016-04-27 22:58:19 +00006518
6519 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006520 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006521 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006522 RegionCodeGenTy RCG(EndThenGen);
6523 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006524 }
6525}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006526
Samuel Antao8d2d7302016-05-26 18:30:22 +00006527void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00006528 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6529 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006530 if (!CGF.HaveInsertPoint())
6531 return;
6532
Samuel Antao8dd66282016-04-27 23:14:30 +00006533 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00006534 isa<OMPTargetExitDataDirective>(D) ||
6535 isa<OMPTargetUpdateDirective>(D)) &&
6536 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00006537
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006538 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006539 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006540 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006541 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006542 MappableExprsHandler::MapValuesArrayTy Pointers;
6543 MappableExprsHandler::MapValuesArrayTy Sizes;
6544 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6545
6546 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00006547 MappableExprsHandler MEHandler(D, CGF);
6548 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006549
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006550 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006551 TargetDataInfo Info;
6552 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6553 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6554 Info.PointersArray, Info.SizesArray,
6555 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006556
6557 // Emit device ID if any.
6558 llvm::Value *DeviceID = nullptr;
6559 if (Device)
6560 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6561 CGF.Int32Ty, /*isSigned=*/true);
6562 else
6563 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6564
6565 // Emit the number of elements in the offloading arrays.
6566 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6567
6568 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006569 DeviceID, PointerNum, Info.BasePointersArray,
6570 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00006571
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006572 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00006573 // Select the right runtime function call for each expected standalone
6574 // directive.
6575 OpenMPRTLFunction RTLFn;
6576 switch (D.getDirectiveKind()) {
6577 default:
6578 llvm_unreachable("Unexpected standalone target data directive.");
6579 break;
6580 case OMPD_target_enter_data:
6581 RTLFn = OMPRTL__tgt_target_data_begin;
6582 break;
6583 case OMPD_target_exit_data:
6584 RTLFn = OMPRTL__tgt_target_data_end;
6585 break;
6586 case OMPD_target_update:
6587 RTLFn = OMPRTL__tgt_target_data_update;
6588 break;
6589 }
6590 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006591 };
6592
6593 // In the event we get an if clause, we don't have to take any action on the
6594 // else side.
6595 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6596
6597 if (IfCond) {
6598 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6599 } else {
6600 RegionCodeGenTy ThenGenRCG(ThenGen);
6601 ThenGenRCG(CGF);
6602 }
6603}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006604
6605namespace {
6606 /// Kind of parameter in a function with 'declare simd' directive.
6607 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6608 /// Attribute set of the parameter.
6609 struct ParamAttrTy {
6610 ParamKindTy Kind = Vector;
6611 llvm::APSInt StrideOrArg;
6612 llvm::APSInt Alignment;
6613 };
6614} // namespace
6615
6616static unsigned evaluateCDTSize(const FunctionDecl *FD,
6617 ArrayRef<ParamAttrTy> ParamAttrs) {
6618 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6619 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6620 // of that clause. The VLEN value must be power of 2.
6621 // In other case the notion of the function`s "characteristic data type" (CDT)
6622 // is used to compute the vector length.
6623 // CDT is defined in the following order:
6624 // a) For non-void function, the CDT is the return type.
6625 // b) If the function has any non-uniform, non-linear parameters, then the
6626 // CDT is the type of the first such parameter.
6627 // c) If the CDT determined by a) or b) above is struct, union, or class
6628 // type which is pass-by-value (except for the type that maps to the
6629 // built-in complex data type), the characteristic data type is int.
6630 // d) If none of the above three cases is applicable, the CDT is int.
6631 // The VLEN is then determined based on the CDT and the size of vector
6632 // register of that ISA for which current vector version is generated. The
6633 // VLEN is computed using the formula below:
6634 // VLEN = sizeof(vector_register) / sizeof(CDT),
6635 // where vector register size specified in section 3.2.1 Registers and the
6636 // Stack Frame of original AMD64 ABI document.
6637 QualType RetType = FD->getReturnType();
6638 if (RetType.isNull())
6639 return 0;
6640 ASTContext &C = FD->getASTContext();
6641 QualType CDT;
6642 if (!RetType.isNull() && !RetType->isVoidType())
6643 CDT = RetType;
6644 else {
6645 unsigned Offset = 0;
6646 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6647 if (ParamAttrs[Offset].Kind == Vector)
6648 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6649 ++Offset;
6650 }
6651 if (CDT.isNull()) {
6652 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6653 if (ParamAttrs[I + Offset].Kind == Vector) {
6654 CDT = FD->getParamDecl(I)->getType();
6655 break;
6656 }
6657 }
6658 }
6659 }
6660 if (CDT.isNull())
6661 CDT = C.IntTy;
6662 CDT = CDT->getCanonicalTypeUnqualified();
6663 if (CDT->isRecordType() || CDT->isUnionType())
6664 CDT = C.IntTy;
6665 return C.getTypeSize(CDT);
6666}
6667
6668static void
6669emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00006670 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006671 ArrayRef<ParamAttrTy> ParamAttrs,
6672 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6673 struct ISADataTy {
6674 char ISA;
6675 unsigned VecRegSize;
6676 };
6677 ISADataTy ISAData[] = {
6678 {
6679 'b', 128
6680 }, // SSE
6681 {
6682 'c', 256
6683 }, // AVX
6684 {
6685 'd', 256
6686 }, // AVX2
6687 {
6688 'e', 512
6689 }, // AVX512
6690 };
6691 llvm::SmallVector<char, 2> Masked;
6692 switch (State) {
6693 case OMPDeclareSimdDeclAttr::BS_Undefined:
6694 Masked.push_back('N');
6695 Masked.push_back('M');
6696 break;
6697 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6698 Masked.push_back('N');
6699 break;
6700 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6701 Masked.push_back('M');
6702 break;
6703 }
6704 for (auto Mask : Masked) {
6705 for (auto &Data : ISAData) {
6706 SmallString<256> Buffer;
6707 llvm::raw_svector_ostream Out(Buffer);
6708 Out << "_ZGV" << Data.ISA << Mask;
6709 if (!VLENVal) {
6710 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6711 evaluateCDTSize(FD, ParamAttrs));
6712 } else
6713 Out << VLENVal;
6714 for (auto &ParamAttr : ParamAttrs) {
6715 switch (ParamAttr.Kind){
6716 case LinearWithVarStride:
6717 Out << 's' << ParamAttr.StrideOrArg;
6718 break;
6719 case Linear:
6720 Out << 'l';
6721 if (!!ParamAttr.StrideOrArg)
6722 Out << ParamAttr.StrideOrArg;
6723 break;
6724 case Uniform:
6725 Out << 'u';
6726 break;
6727 case Vector:
6728 Out << 'v';
6729 break;
6730 }
6731 if (!!ParamAttr.Alignment)
6732 Out << 'a' << ParamAttr.Alignment;
6733 }
6734 Out << '_' << Fn->getName();
6735 Fn->addFnAttr(Out.str());
6736 }
6737 }
6738}
6739
6740void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6741 llvm::Function *Fn) {
6742 ASTContext &C = CGM.getContext();
6743 FD = FD->getCanonicalDecl();
6744 // Map params to their positions in function decl.
6745 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6746 if (isa<CXXMethodDecl>(FD))
6747 ParamPositions.insert({FD, 0});
6748 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00006749 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006750 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6751 ++ParamPos;
6752 }
6753 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6754 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6755 // Mark uniform parameters.
6756 for (auto *E : Attr->uniforms()) {
6757 E = E->IgnoreParenImpCasts();
6758 unsigned Pos;
6759 if (isa<CXXThisExpr>(E))
6760 Pos = ParamPositions[FD];
6761 else {
6762 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6763 ->getCanonicalDecl();
6764 Pos = ParamPositions[PVD];
6765 }
6766 ParamAttrs[Pos].Kind = Uniform;
6767 }
6768 // Get alignment info.
6769 auto NI = Attr->alignments_begin();
6770 for (auto *E : Attr->aligneds()) {
6771 E = E->IgnoreParenImpCasts();
6772 unsigned Pos;
6773 QualType ParmTy;
6774 if (isa<CXXThisExpr>(E)) {
6775 Pos = ParamPositions[FD];
6776 ParmTy = E->getType();
6777 } else {
6778 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6779 ->getCanonicalDecl();
6780 Pos = ParamPositions[PVD];
6781 ParmTy = PVD->getType();
6782 }
6783 ParamAttrs[Pos].Alignment =
6784 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6785 : llvm::APSInt::getUnsigned(
6786 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6787 .getQuantity());
6788 ++NI;
6789 }
6790 // Mark linear parameters.
6791 auto SI = Attr->steps_begin();
6792 auto MI = Attr->modifiers_begin();
6793 for (auto *E : Attr->linears()) {
6794 E = E->IgnoreParenImpCasts();
6795 unsigned Pos;
6796 if (isa<CXXThisExpr>(E))
6797 Pos = ParamPositions[FD];
6798 else {
6799 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6800 ->getCanonicalDecl();
6801 Pos = ParamPositions[PVD];
6802 }
6803 auto &ParamAttr = ParamAttrs[Pos];
6804 ParamAttr.Kind = Linear;
6805 if (*SI) {
6806 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6807 Expr::SE_AllowSideEffects)) {
6808 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6809 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6810 ParamAttr.Kind = LinearWithVarStride;
6811 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6812 ParamPositions[StridePVD->getCanonicalDecl()]);
6813 }
6814 }
6815 }
6816 }
6817 ++SI;
6818 ++MI;
6819 }
6820 llvm::APSInt VLENVal;
6821 if (const Expr *VLEN = Attr->getSimdlen())
6822 VLENVal = VLEN->EvaluateKnownConstInt(C);
6823 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6824 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6825 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6826 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6827 }
6828}
Alexey Bataev8b427062016-05-25 12:36:08 +00006829
6830namespace {
6831/// Cleanup action for doacross support.
6832class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6833public:
6834 static const int DoacrossFinArgs = 2;
6835
6836private:
6837 llvm::Value *RTLFn;
6838 llvm::Value *Args[DoacrossFinArgs];
6839
6840public:
6841 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6842 : RTLFn(RTLFn) {
6843 assert(CallArgs.size() == DoacrossFinArgs);
6844 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6845 }
6846 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6847 if (!CGF.HaveInsertPoint())
6848 return;
6849 CGF.EmitRuntimeCall(RTLFn, Args);
6850 }
6851};
6852} // namespace
6853
6854void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6855 const OMPLoopDirective &D) {
6856 if (!CGF.HaveInsertPoint())
6857 return;
6858
6859 ASTContext &C = CGM.getContext();
6860 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6861 RecordDecl *RD;
6862 if (KmpDimTy.isNull()) {
6863 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6864 // kmp_int64 lo; // lower
6865 // kmp_int64 up; // upper
6866 // kmp_int64 st; // stride
6867 // };
6868 RD = C.buildImplicitRecord("kmp_dim");
6869 RD->startDefinition();
6870 addFieldToRecordDecl(C, RD, Int64Ty);
6871 addFieldToRecordDecl(C, RD, Int64Ty);
6872 addFieldToRecordDecl(C, RD, Int64Ty);
6873 RD->completeDefinition();
6874 KmpDimTy = C.getRecordType(RD);
6875 } else
6876 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6877
6878 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6879 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6880 enum { LowerFD = 0, UpperFD, StrideFD };
6881 // Fill dims with data.
6882 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6883 // dims.upper = num_iterations;
6884 LValue UpperLVal =
6885 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6886 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6887 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6888 Int64Ty, D.getNumIterations()->getExprLoc());
6889 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6890 // dims.stride = 1;
6891 LValue StrideLVal =
6892 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6893 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6894 StrideLVal);
6895
6896 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6897 // kmp_int32 num_dims, struct kmp_dim * dims);
6898 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6899 getThreadID(CGF, D.getLocStart()),
6900 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6901 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6902 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6903
6904 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6905 CGF.EmitRuntimeCall(RTLFn, Args);
6906 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6907 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6908 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6909 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6910 llvm::makeArrayRef(FiniArgs));
6911}
6912
6913void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6914 const OMPDependClause *C) {
6915 QualType Int64Ty =
6916 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6917 const Expr *CounterVal = C->getCounterValue();
6918 assert(CounterVal);
6919 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6920 CounterVal->getType(), Int64Ty,
6921 CounterVal->getExprLoc());
6922 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6923 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6924 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6925 getThreadID(CGF, C->getLocStart()),
6926 CntAddr.getPointer()};
6927 llvm::Value *RTLFn;
6928 if (C->getDependencyKind() == OMPC_DEPEND_source)
6929 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6930 else {
6931 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6932 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6933 }
6934 CGF.EmitRuntimeCall(RTLFn, Args);
6935}
6936