blob: 05aff9d92b1eb09f128bda2659cfa34e84bad01f [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 McCall6c9f1fdb2016-11-19 08:17:24 +000018#include "ConstantBuilder.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,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000102 OpenMPDirectiveKind Kind, bool HasCancel)
103 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
104 HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000105 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000106 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
107 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000108
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000109 /// \brief Get a variable or parameter for storing global thread id
110 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000111 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000112
Alexey Bataev18095712014-10-10 12:19:54 +0000113 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000114 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +0000115
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000116 static bool classof(const CGCapturedStmtInfo *Info) {
117 return CGOpenMPRegionInfo::classof(Info) &&
118 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
119 ParallelOutlinedRegion;
120 }
121
Alexey Bataev18095712014-10-10 12:19:54 +0000122private:
123 /// \brief A variable or parameter storing global thread id for OpenMP
124 /// constructs.
125 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000126};
127
Alexey Bataev62b63b12015-03-10 07:28:44 +0000128/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000129class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000130public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000131 class UntiedTaskActionTy final : public PrePostActionTy {
132 bool Untied;
133 const VarDecl *PartIDVar;
134 const RegionCodeGenTy UntiedCodeGen;
135 llvm::SwitchInst *UntiedSwitch = nullptr;
136
137 public:
138 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
139 const RegionCodeGenTy &UntiedCodeGen)
140 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
141 void Enter(CodeGenFunction &CGF) override {
142 if (Untied) {
143 // Emit task switching point.
144 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
145 CGF.GetAddrOfLocalVar(PartIDVar),
146 PartIDVar->getType()->castAs<PointerType>());
147 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
148 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
149 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
150 CGF.EmitBlock(DoneBB);
151 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
152 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
153 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
154 CGF.Builder.GetInsertBlock());
155 emitUntiedSwitch(CGF);
156 }
157 }
158 void emitUntiedSwitch(CodeGenFunction &CGF) const {
159 if (Untied) {
160 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
161 CGF.GetAddrOfLocalVar(PartIDVar),
162 PartIDVar->getType()->castAs<PointerType>());
163 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
164 PartIdLVal);
165 UntiedCodeGen(CGF);
166 CodeGenFunction::JumpDest CurPoint =
167 CGF.getJumpDestInCurrentScope(".untied.next.");
168 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
169 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
170 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
171 CGF.Builder.GetInsertBlock());
172 CGF.EmitBranchThroughCleanup(CurPoint);
173 CGF.EmitBlock(CurPoint.getBlock());
174 }
175 }
176 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
177 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000178 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000179 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000180 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000181 OpenMPDirectiveKind Kind, bool HasCancel,
182 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000183 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000185 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
186 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000187
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 /// \brief Get a variable or parameter for storing global thread id
189 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000190 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191
192 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
Alexey Bataev62b63b12015-03-10 07:28:44 +0000195 /// \brief Get the name of the capture helper.
196 StringRef getHelperName() const override { return ".omp_outlined."; }
197
Alexey Bataev48591dd2016-04-20 04:01:36 +0000198 void emitUntiedSwitch(CodeGenFunction &CGF) override {
199 Action.emitUntiedSwitch(CGF);
200 }
201
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000202 static bool classof(const CGCapturedStmtInfo *Info) {
203 return CGOpenMPRegionInfo::classof(Info) &&
204 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
205 TaskOutlinedRegion;
206 }
207
Alexey Bataev62b63b12015-03-10 07:28:44 +0000208private:
209 /// \brief A variable or parameter storing global thread id for OpenMP
210 /// constructs.
211 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000212 /// Action for emitting code for untied tasks.
213 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000214};
215
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000216/// \brief API for inlined captured statement code generation in OpenMP
217/// constructs.
218class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
219public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000220 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000221 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000222 OpenMPDirectiveKind Kind, bool HasCancel)
223 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
224 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000225 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000226
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000227 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000228 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000229 if (OuterRegionInfo)
230 return OuterRegionInfo->getContextValue();
231 llvm_unreachable("No context value for inlined OpenMP region");
232 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000233
Hans Wennborg7eb54642015-09-10 17:07:54 +0000234 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000235 if (OuterRegionInfo) {
236 OuterRegionInfo->setContextValue(V);
237 return;
238 }
239 llvm_unreachable("No context value for inlined OpenMP region");
240 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000241
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000242 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000243 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000244 if (OuterRegionInfo)
245 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000246 // If there is no outer outlined region,no need to lookup in a list of
247 // captured variables, we can use the original one.
248 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000249 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000250
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000251 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 if (OuterRegionInfo)
253 return OuterRegionInfo->getThisFieldDecl();
254 return nullptr;
255 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000256
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000257 /// \brief Get a variable or parameter for storing global thread id
258 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000259 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 if (OuterRegionInfo)
261 return OuterRegionInfo->getThreadIDVariable();
262 return nullptr;
263 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000264
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000265 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000266 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000267 if (auto *OuterRegionInfo = getOldCSI())
268 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000269 llvm_unreachable("No helper name for inlined OpenMP construct");
270 }
271
Alexey Bataev48591dd2016-04-20 04:01:36 +0000272 void emitUntiedSwitch(CodeGenFunction &CGF) override {
273 if (OuterRegionInfo)
274 OuterRegionInfo->emitUntiedSwitch(CGF);
275 }
276
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000277 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
278
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000279 static bool classof(const CGCapturedStmtInfo *Info) {
280 return CGOpenMPRegionInfo::classof(Info) &&
281 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
282 }
283
Alexey Bataev48591dd2016-04-20 04:01:36 +0000284 ~CGOpenMPInlinedRegionInfo() override = default;
285
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000286private:
287 /// \brief CodeGen info about outer OpenMP region.
288 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
289 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000290};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000291
Samuel Antaobed3c462015-10-02 16:14:20 +0000292/// \brief API for captured statement code generation in OpenMP target
293/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000294/// captured fields. The name of the target region has to be unique in a given
295/// application so it is provided by the client, because only the client has
296/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000297class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000298public:
299 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000300 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000301 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000302 /*HasCancel=*/false),
303 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000304
305 /// \brief This is unused for target regions because each starts executing
306 /// with a single thread.
307 const VarDecl *getThreadIDVariable() const override { return nullptr; }
308
309 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000310 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000311
312 static bool classof(const CGCapturedStmtInfo *Info) {
313 return CGOpenMPRegionInfo::classof(Info) &&
314 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
315 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000316
317private:
318 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000319};
320
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000321static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000322 llvm_unreachable("No codegen for expressions");
323}
324/// \brief API for generation of expressions captured in a innermost OpenMP
325/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000326class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000327public:
328 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
329 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
330 OMPD_unknown,
331 /*HasCancel=*/false),
332 PrivScope(CGF) {
333 // Make sure the globals captured in the provided statement are local by
334 // using the privatization logic. We assume the same variable is not
335 // captured more than once.
336 for (auto &C : CS.captures()) {
337 if (!C.capturesVariable() && !C.capturesVariableByCopy())
338 continue;
339
340 const VarDecl *VD = C.getCapturedVar();
341 if (VD->isLocalVarDeclOrParm())
342 continue;
343
344 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
345 /*RefersToEnclosingVariableOrCapture=*/false,
346 VD->getType().getNonReferenceType(), VK_LValue,
347 SourceLocation());
348 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
349 return CGF.EmitLValue(&DRE).getAddress();
350 });
351 }
352 (void)PrivScope.Privatize();
353 }
354
355 /// \brief Lookup the captured field decl for a variable.
356 const FieldDecl *lookup(const VarDecl *VD) const override {
357 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
358 return FD;
359 return nullptr;
360 }
361
362 /// \brief Emit the captured statement body.
363 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
364 llvm_unreachable("No body for expressions");
365 }
366
367 /// \brief Get a variable or parameter for storing global thread id
368 /// inside OpenMP construct.
369 const VarDecl *getThreadIDVariable() const override {
370 llvm_unreachable("No thread id for expressions");
371 }
372
373 /// \brief Get the name of the capture helper.
374 StringRef getHelperName() const override {
375 llvm_unreachable("No helper name for expressions");
376 }
377
378 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
379
380private:
381 /// Private scope to capture global variables.
382 CodeGenFunction::OMPPrivateScope PrivScope;
383};
384
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000385/// \brief RAII for emitting code of OpenMP constructs.
386class InlinedOpenMPRegionRAII {
387 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000388 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
389 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000390
391public:
392 /// \brief Constructs region for combined constructs.
393 /// \param CodeGen Code generation sequence for combined directives. Includes
394 /// a list of functions used for code generation of implicitly inlined
395 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000396 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000397 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000398 : CGF(CGF) {
399 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000400 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
401 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000402 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
403 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
404 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000405 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000406
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000407 ~InlinedOpenMPRegionRAII() {
408 // Restore original CapturedStmtInfo only if we're done with code emission.
409 auto *OldCSI =
410 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
411 delete CGF.CapturedStmtInfo;
412 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000413 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
414 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000415 }
416};
417
Alexey Bataev50b3c952016-02-19 10:38:26 +0000418/// \brief Values for bit flags used in the ident_t to describe the fields.
419/// All enumeric elements are named and described in accordance with the code
420/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
421enum OpenMPLocationFlags {
422 /// \brief Use trampoline for internal microtask.
423 OMP_IDENT_IMD = 0x01,
424 /// \brief Use c-style ident structure.
425 OMP_IDENT_KMPC = 0x02,
426 /// \brief Atomic reduction option for kmpc_reduce.
427 OMP_ATOMIC_REDUCE = 0x10,
428 /// \brief Explicit 'barrier' directive.
429 OMP_IDENT_BARRIER_EXPL = 0x20,
430 /// \brief Implicit barrier in code.
431 OMP_IDENT_BARRIER_IMPL = 0x40,
432 /// \brief Implicit barrier in 'for' directive.
433 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
434 /// \brief Implicit barrier in 'sections' directive.
435 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
436 /// \brief Implicit barrier in 'single' directive.
437 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
438};
439
440/// \brief Describes ident structure that describes a source location.
441/// All descriptions are taken from
442/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
443/// Original structure:
444/// typedef struct ident {
445/// kmp_int32 reserved_1; /**< might be used in Fortran;
446/// see above */
447/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
448/// KMP_IDENT_KMPC identifies this union
449/// member */
450/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
451/// see above */
452///#if USE_ITT_BUILD
453/// /* but currently used for storing
454/// region-specific ITT */
455/// /* contextual information. */
456///#endif /* USE_ITT_BUILD */
457/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
458/// C++ */
459/// char const *psource; /**< String describing the source location.
460/// The string is composed of semi-colon separated
461// fields which describe the source file,
462/// the function and a pair of line numbers that
463/// delimit the construct.
464/// */
465/// } ident_t;
466enum IdentFieldIndex {
467 /// \brief might be used in Fortran
468 IdentField_Reserved_1,
469 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
470 IdentField_Flags,
471 /// \brief Not really used in Fortran any more
472 IdentField_Reserved_2,
473 /// \brief Source[4] in Fortran, do not use for C++
474 IdentField_Reserved_3,
475 /// \brief String describing the source location. The string is composed of
476 /// semi-colon separated fields which describe the source file, the function
477 /// and a pair of line numbers that delimit the construct.
478 IdentField_PSource
479};
480
481/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
482/// the enum sched_type in kmp.h).
483enum OpenMPSchedType {
484 /// \brief Lower bound for default (unordered) versions.
485 OMP_sch_lower = 32,
486 OMP_sch_static_chunked = 33,
487 OMP_sch_static = 34,
488 OMP_sch_dynamic_chunked = 35,
489 OMP_sch_guided_chunked = 36,
490 OMP_sch_runtime = 37,
491 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000492 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000493 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000494 /// \brief Lower bound for 'ordered' versions.
495 OMP_ord_lower = 64,
496 OMP_ord_static_chunked = 65,
497 OMP_ord_static = 66,
498 OMP_ord_dynamic_chunked = 67,
499 OMP_ord_guided_chunked = 68,
500 OMP_ord_runtime = 69,
501 OMP_ord_auto = 70,
502 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000503 /// \brief dist_schedule types
504 OMP_dist_sch_static_chunked = 91,
505 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000506 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
507 /// Set if the monotonic schedule modifier was present.
508 OMP_sch_modifier_monotonic = (1 << 29),
509 /// Set if the nonmonotonic schedule modifier was present.
510 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000511};
512
513enum OpenMPRTLFunction {
514 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
515 /// kmpc_micro microtask, ...);
516 OMPRTL__kmpc_fork_call,
517 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
518 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
519 OMPRTL__kmpc_threadprivate_cached,
520 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
521 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
522 OMPRTL__kmpc_threadprivate_register,
523 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
524 OMPRTL__kmpc_global_thread_num,
525 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
526 // kmp_critical_name *crit);
527 OMPRTL__kmpc_critical,
528 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
529 // global_tid, kmp_critical_name *crit, uintptr_t hint);
530 OMPRTL__kmpc_critical_with_hint,
531 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
532 // kmp_critical_name *crit);
533 OMPRTL__kmpc_end_critical,
534 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
535 // global_tid);
536 OMPRTL__kmpc_cancel_barrier,
537 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
538 OMPRTL__kmpc_barrier,
539 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
540 OMPRTL__kmpc_for_static_fini,
541 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
542 // global_tid);
543 OMPRTL__kmpc_serialized_parallel,
544 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
545 // global_tid);
546 OMPRTL__kmpc_end_serialized_parallel,
547 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
548 // kmp_int32 num_threads);
549 OMPRTL__kmpc_push_num_threads,
550 // Call to void __kmpc_flush(ident_t *loc);
551 OMPRTL__kmpc_flush,
552 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
553 OMPRTL__kmpc_master,
554 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
555 OMPRTL__kmpc_end_master,
556 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
557 // int end_part);
558 OMPRTL__kmpc_omp_taskyield,
559 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
560 OMPRTL__kmpc_single,
561 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
562 OMPRTL__kmpc_end_single,
563 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
564 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
565 // kmp_routine_entry_t *task_entry);
566 OMPRTL__kmpc_omp_task_alloc,
567 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
568 // new_task);
569 OMPRTL__kmpc_omp_task,
570 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
571 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
572 // kmp_int32 didit);
573 OMPRTL__kmpc_copyprivate,
574 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
575 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
576 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
577 OMPRTL__kmpc_reduce,
578 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
579 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
580 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
581 // *lck);
582 OMPRTL__kmpc_reduce_nowait,
583 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
584 // kmp_critical_name *lck);
585 OMPRTL__kmpc_end_reduce,
586 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
587 // kmp_critical_name *lck);
588 OMPRTL__kmpc_end_reduce_nowait,
589 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
590 // kmp_task_t * new_task);
591 OMPRTL__kmpc_omp_task_begin_if0,
592 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
593 // kmp_task_t * new_task);
594 OMPRTL__kmpc_omp_task_complete_if0,
595 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
596 OMPRTL__kmpc_ordered,
597 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
598 OMPRTL__kmpc_end_ordered,
599 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
600 // global_tid);
601 OMPRTL__kmpc_omp_taskwait,
602 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
603 OMPRTL__kmpc_taskgroup,
604 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
605 OMPRTL__kmpc_end_taskgroup,
606 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
607 // int proc_bind);
608 OMPRTL__kmpc_push_proc_bind,
609 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
610 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
611 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
612 OMPRTL__kmpc_omp_task_with_deps,
613 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
614 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
615 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
616 OMPRTL__kmpc_omp_wait_deps,
617 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
618 // global_tid, kmp_int32 cncl_kind);
619 OMPRTL__kmpc_cancellationpoint,
620 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
621 // kmp_int32 cncl_kind);
622 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000623 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
624 // kmp_int32 num_teams, kmp_int32 thread_limit);
625 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000626 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
627 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000628 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000629 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
630 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
631 // sched, kmp_uint64 grainsize, void *task_dup);
632 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000633 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
634 // num_dims, struct kmp_dim *dims);
635 OMPRTL__kmpc_doacross_init,
636 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
637 OMPRTL__kmpc_doacross_fini,
638 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
639 // *vec);
640 OMPRTL__kmpc_doacross_post,
641 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
642 // *vec);
643 OMPRTL__kmpc_doacross_wait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000644
645 //
646 // Offloading related calls
647 //
648 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
649 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
650 // *arg_types);
651 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000652 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
653 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
654 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
655 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000656 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
657 OMPRTL__tgt_register_lib,
658 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
659 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000660 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
661 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
662 OMPRTL__tgt_target_data_begin,
663 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
664 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
665 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000666 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
667 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
668 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000669};
670
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000671/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
672/// region.
673class CleanupTy final : public EHScopeStack::Cleanup {
674 PrePostActionTy *Action;
675
676public:
677 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
678 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
679 if (!CGF.HaveInsertPoint())
680 return;
681 Action->Exit(CGF);
682 }
683};
684
Hans Wennborg7eb54642015-09-10 17:07:54 +0000685} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000686
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000687void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
688 CodeGenFunction::RunCleanupsScope Scope(CGF);
689 if (PrePostAction) {
690 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
691 Callback(CodeGen, CGF, *PrePostAction);
692 } else {
693 PrePostActionTy Action;
694 Callback(CodeGen, CGF, Action);
695 }
696}
697
Alexey Bataev18095712014-10-10 12:19:54 +0000698LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000699 return CGF.EmitLoadOfPointerLValue(
700 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
701 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000702}
703
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000704void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000705 if (!CGF.HaveInsertPoint())
706 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000707 // 1.2.2 OpenMP Language Terminology
708 // Structured block - An executable statement with a single entry at the
709 // top and a single exit at the bottom.
710 // The point of exit cannot be a branch out of the structured block.
711 // longjmp() and throw() must not violate the entry/exit criteria.
712 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000713 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000714 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000715}
716
Alexey Bataev62b63b12015-03-10 07:28:44 +0000717LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
718 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000719 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
720 getThreadIDVariable()->getType(),
721 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000722}
723
Alexey Bataev9959db52014-05-06 10:08:46 +0000724CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000725 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000726 IdentTy = llvm::StructType::create(
727 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
728 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000729 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000730 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000731
732 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000733}
734
Alexey Bataev91797552015-03-18 04:13:55 +0000735void CGOpenMPRuntime::clear() {
736 InternalVars.clear();
737}
738
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000739static llvm::Function *
740emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
741 const Expr *CombinerInitializer, const VarDecl *In,
742 const VarDecl *Out, bool IsCombiner) {
743 // void .omp_combiner.(Ty *in, Ty *out);
744 auto &C = CGM.getContext();
745 QualType PtrTy = C.getPointerType(Ty).withRestrict();
746 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000747 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
748 /*Id=*/nullptr, PtrTy);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000749 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
750 /*Id=*/nullptr, PtrTy);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000751 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000752 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000753 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000754 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000755 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
756 auto *Fn = llvm::Function::Create(
757 FnTy, llvm::GlobalValue::InternalLinkage,
758 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
759 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000760 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000761 CodeGenFunction CGF(CGM);
762 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
763 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
764 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
765 CodeGenFunction::OMPPrivateScope Scope(CGF);
766 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
767 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
768 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
769 .getAddress();
770 });
771 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
772 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
773 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
774 .getAddress();
775 });
776 (void)Scope.Privatize();
777 CGF.EmitIgnoredExpr(CombinerInitializer);
778 Scope.ForceCleanup();
779 CGF.FinishFunction();
780 return Fn;
781}
782
783void CGOpenMPRuntime::emitUserDefinedReduction(
784 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
785 if (UDRMap.count(D) > 0)
786 return;
787 auto &C = CGM.getContext();
788 if (!In || !Out) {
789 In = &C.Idents.get("omp_in");
790 Out = &C.Idents.get("omp_out");
791 }
792 llvm::Function *Combiner = emitCombinerOrInitializer(
793 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
794 cast<VarDecl>(D->lookup(Out).front()),
795 /*IsCombiner=*/true);
796 llvm::Function *Initializer = nullptr;
797 if (auto *Init = D->getInitializer()) {
798 if (!Priv || !Orig) {
799 Priv = &C.Idents.get("omp_priv");
800 Orig = &C.Idents.get("omp_orig");
801 }
802 Initializer = emitCombinerOrInitializer(
803 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
804 cast<VarDecl>(D->lookup(Priv).front()),
805 /*IsCombiner=*/false);
806 }
807 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
808 if (CGF) {
809 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
810 Decls.second.push_back(D);
811 }
812}
813
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000814std::pair<llvm::Function *, llvm::Function *>
815CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
816 auto I = UDRMap.find(D);
817 if (I != UDRMap.end())
818 return I->second;
819 emitUserDefinedReduction(/*CGF=*/nullptr, D);
820 return UDRMap.lookup(D);
821}
822
John McCall7f416cc2015-09-08 08:05:57 +0000823// Layout information for ident_t.
824static CharUnits getIdentAlign(CodeGenModule &CGM) {
825 return CGM.getPointerAlign();
826}
827static CharUnits getIdentSize(CodeGenModule &CGM) {
828 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
829 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
830}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000831static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000832 // All the fields except the last are i32, so this works beautifully.
833 return unsigned(Field) * CharUnits::fromQuantity(4);
834}
835static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000836 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000837 const llvm::Twine &Name = "") {
838 auto Offset = getOffsetOfIdentField(Field);
839 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
840}
841
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000842llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000843 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
844 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000845 assert(ThreadIDVar->getType()->isPointerType() &&
846 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000847 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
848 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000849 bool HasCancel = false;
850 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
851 HasCancel = OPD->hasCancel();
852 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
853 HasCancel = OPSD->hasCancel();
854 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
855 HasCancel = OPFD->hasCancel();
856 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
857 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000858 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000859 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000860}
861
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000862llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
863 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000864 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
865 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
866 bool Tied, unsigned &NumberOfParts) {
867 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
868 PrePostActionTy &) {
869 auto *ThreadID = getThreadID(CGF, D.getLocStart());
870 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
871 llvm::Value *TaskArgs[] = {
872 UpLoc, ThreadID,
873 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
874 TaskTVar->getType()->castAs<PointerType>())
875 .getPointer()};
876 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
877 };
878 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
879 UntiedCodeGen);
880 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000881 assert(!ThreadIDVar->getType()->isPointerType() &&
882 "thread id variable must be of type kmp_int32 for tasks");
883 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000884 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000885 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000886 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
887 InnermostKind,
888 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000889 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000890 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
891 if (!Tied)
892 NumberOfParts = Action.getNumberOfParts();
893 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000894}
895
Alexey Bataev50b3c952016-02-19 10:38:26 +0000896Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000897 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000898 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000899 if (!Entry) {
900 if (!DefaultOpenMPPSource) {
901 // Initialize default location for psource field of ident_t structure of
902 // all ident_t objects. Format is ";file;function;line;column;;".
903 // Taken from
904 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
905 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000906 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000907 DefaultOpenMPPSource =
908 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
909 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000910
John McCall23c9dc62016-11-28 22:18:27 +0000911 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000912 auto fields = builder.beginStruct(IdentTy);
913 fields.addInt(CGM.Int32Ty, 0);
914 fields.addInt(CGM.Int32Ty, Flags);
915 fields.addInt(CGM.Int32Ty, 0);
916 fields.addInt(CGM.Int32Ty, 0);
917 fields.add(DefaultOpenMPPSource);
918 auto DefaultOpenMPLocation =
919 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
920 llvm::GlobalValue::PrivateLinkage);
921 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
922
John McCall7f416cc2015-09-08 08:05:57 +0000923 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000924 }
John McCall7f416cc2015-09-08 08:05:57 +0000925 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000926}
927
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000928llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
929 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000930 unsigned Flags) {
931 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000932 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000933 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000934 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000935 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000936
937 assert(CGF.CurFn && "No function in current CodeGenFunction.");
938
John McCall7f416cc2015-09-08 08:05:57 +0000939 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000940 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
941 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000942 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
943
Alexander Musmanc6388682014-12-15 07:07:06 +0000944 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
945 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000946 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000947 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000948 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
949 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000950 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000951 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000952 LocValue = AI;
953
954 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
955 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000956 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000957 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000958 }
959
960 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000961 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000962
Alexey Bataevf002aca2014-05-30 05:48:40 +0000963 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
964 if (OMPDebugLoc == nullptr) {
965 SmallString<128> Buffer2;
966 llvm::raw_svector_ostream OS2(Buffer2);
967 // Build debug location
968 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
969 OS2 << ";" << PLoc.getFilename() << ";";
970 if (const FunctionDecl *FD =
971 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
972 OS2 << FD->getQualifiedNameAsString();
973 }
974 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
975 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
976 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000977 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000978 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000979 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
980
John McCall7f416cc2015-09-08 08:05:57 +0000981 // Our callers always pass this to a runtime function, so for
982 // convenience, go ahead and return a naked pointer.
983 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000984}
985
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000986llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
987 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000988 assert(CGF.CurFn && "No function in current CodeGenFunction.");
989
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000990 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000991 // Check whether we've already cached a load of the thread id in this
992 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000993 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000994 if (I != OpenMPLocThreadIDMap.end()) {
995 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000996 if (ThreadID != nullptr)
997 return ThreadID;
998 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000999 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001000 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001001 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001002 // Check if this an outlined function with thread id passed as argument.
1003 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001004 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1005 // If value loaded in entry block, cache it and use it everywhere in
1006 // function.
1007 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1008 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1009 Elem.second.ThreadID = ThreadID;
1010 }
1011 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001012 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001013 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001014
1015 // This is not an outlined function region - need to call __kmpc_int32
1016 // kmpc_global_thread_num(ident_t *loc).
1017 // Generate thread id value and cache this value for use across the
1018 // function.
1019 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1020 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1021 ThreadID =
1022 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1023 emitUpdateLocation(CGF, Loc));
1024 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1025 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001026 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001027}
1028
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001029void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001030 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001031 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1032 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001033 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1034 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1035 UDRMap.erase(D);
1036 }
1037 FunctionUDRMap.erase(CGF.CurFn);
1038 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001039}
1040
1041llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001042 if (!IdentTy) {
1043 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001044 return llvm::PointerType::getUnqual(IdentTy);
1045}
1046
1047llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001048 if (!Kmpc_MicroTy) {
1049 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1050 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1051 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1052 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1053 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001054 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1055}
1056
1057llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001058CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001059 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001060 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001061 case OMPRTL__kmpc_fork_call: {
1062 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1063 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001064 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1065 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001066 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001067 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001068 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1069 break;
1070 }
1071 case OMPRTL__kmpc_global_thread_num: {
1072 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001073 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001074 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001075 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001076 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1077 break;
1078 }
Alexey Bataev97720002014-11-11 04:05:39 +00001079 case OMPRTL__kmpc_threadprivate_cached: {
1080 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1081 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1082 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1083 CGM.VoidPtrTy, CGM.SizeTy,
1084 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1085 llvm::FunctionType *FnTy =
1086 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1087 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1088 break;
1089 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001090 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001091 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1092 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001093 llvm::Type *TypeParams[] = {
1094 getIdentTyPointerTy(), CGM.Int32Ty,
1095 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1096 llvm::FunctionType *FnTy =
1097 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1098 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1099 break;
1100 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001101 case OMPRTL__kmpc_critical_with_hint: {
1102 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1103 // kmp_critical_name *crit, uintptr_t hint);
1104 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1105 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1106 CGM.IntPtrTy};
1107 llvm::FunctionType *FnTy =
1108 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1109 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1110 break;
1111 }
Alexey Bataev97720002014-11-11 04:05:39 +00001112 case OMPRTL__kmpc_threadprivate_register: {
1113 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1114 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1115 // typedef void *(*kmpc_ctor)(void *);
1116 auto KmpcCtorTy =
1117 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1118 /*isVarArg*/ false)->getPointerTo();
1119 // typedef void *(*kmpc_cctor)(void *, void *);
1120 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1121 auto KmpcCopyCtorTy =
1122 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1123 /*isVarArg*/ false)->getPointerTo();
1124 // typedef void (*kmpc_dtor)(void *);
1125 auto KmpcDtorTy =
1126 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1127 ->getPointerTo();
1128 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1129 KmpcCopyCtorTy, KmpcDtorTy};
1130 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1131 /*isVarArg*/ false);
1132 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1133 break;
1134 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001135 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001136 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1137 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001138 llvm::Type *TypeParams[] = {
1139 getIdentTyPointerTy(), CGM.Int32Ty,
1140 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1141 llvm::FunctionType *FnTy =
1142 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1143 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1144 break;
1145 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001146 case OMPRTL__kmpc_cancel_barrier: {
1147 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1148 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001149 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1150 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001151 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1152 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001153 break;
1154 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001155 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001156 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001157 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1158 llvm::FunctionType *FnTy =
1159 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1160 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1161 break;
1162 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001163 case OMPRTL__kmpc_for_static_fini: {
1164 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1165 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1166 llvm::FunctionType *FnTy =
1167 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1168 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1169 break;
1170 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001171 case OMPRTL__kmpc_push_num_threads: {
1172 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1173 // kmp_int32 num_threads)
1174 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1175 CGM.Int32Ty};
1176 llvm::FunctionType *FnTy =
1177 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1178 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1179 break;
1180 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001181 case OMPRTL__kmpc_serialized_parallel: {
1182 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1183 // global_tid);
1184 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1185 llvm::FunctionType *FnTy =
1186 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1187 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1188 break;
1189 }
1190 case OMPRTL__kmpc_end_serialized_parallel: {
1191 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1192 // global_tid);
1193 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1194 llvm::FunctionType *FnTy =
1195 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1196 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1197 break;
1198 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001199 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001200 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001201 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1202 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001203 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001204 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1205 break;
1206 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001207 case OMPRTL__kmpc_master: {
1208 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1209 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1210 llvm::FunctionType *FnTy =
1211 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1212 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1213 break;
1214 }
1215 case OMPRTL__kmpc_end_master: {
1216 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1217 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1218 llvm::FunctionType *FnTy =
1219 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1220 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1221 break;
1222 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001223 case OMPRTL__kmpc_omp_taskyield: {
1224 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1225 // int end_part);
1226 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1227 llvm::FunctionType *FnTy =
1228 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1229 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1230 break;
1231 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001232 case OMPRTL__kmpc_single: {
1233 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1234 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1235 llvm::FunctionType *FnTy =
1236 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1237 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1238 break;
1239 }
1240 case OMPRTL__kmpc_end_single: {
1241 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1242 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1243 llvm::FunctionType *FnTy =
1244 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1245 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1246 break;
1247 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001248 case OMPRTL__kmpc_omp_task_alloc: {
1249 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1250 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1251 // kmp_routine_entry_t *task_entry);
1252 assert(KmpRoutineEntryPtrTy != nullptr &&
1253 "Type kmp_routine_entry_t must be created.");
1254 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1255 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1256 // Return void * and then cast to particular kmp_task_t type.
1257 llvm::FunctionType *FnTy =
1258 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1259 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1260 break;
1261 }
1262 case OMPRTL__kmpc_omp_task: {
1263 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1264 // *new_task);
1265 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1266 CGM.VoidPtrTy};
1267 llvm::FunctionType *FnTy =
1268 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1269 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1270 break;
1271 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001272 case OMPRTL__kmpc_copyprivate: {
1273 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001274 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001275 // kmp_int32 didit);
1276 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1277 auto *CpyFnTy =
1278 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001279 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001280 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1281 CGM.Int32Ty};
1282 llvm::FunctionType *FnTy =
1283 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1284 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1285 break;
1286 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001287 case OMPRTL__kmpc_reduce: {
1288 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1289 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1290 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1291 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1292 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1293 /*isVarArg=*/false);
1294 llvm::Type *TypeParams[] = {
1295 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1296 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1297 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1298 llvm::FunctionType *FnTy =
1299 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1300 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1301 break;
1302 }
1303 case OMPRTL__kmpc_reduce_nowait: {
1304 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1305 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1306 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1307 // *lck);
1308 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1309 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1310 /*isVarArg=*/false);
1311 llvm::Type *TypeParams[] = {
1312 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1313 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1314 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1315 llvm::FunctionType *FnTy =
1316 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1317 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1318 break;
1319 }
1320 case OMPRTL__kmpc_end_reduce: {
1321 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1322 // kmp_critical_name *lck);
1323 llvm::Type *TypeParams[] = {
1324 getIdentTyPointerTy(), CGM.Int32Ty,
1325 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1326 llvm::FunctionType *FnTy =
1327 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1328 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1329 break;
1330 }
1331 case OMPRTL__kmpc_end_reduce_nowait: {
1332 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1333 // kmp_critical_name *lck);
1334 llvm::Type *TypeParams[] = {
1335 getIdentTyPointerTy(), CGM.Int32Ty,
1336 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1337 llvm::FunctionType *FnTy =
1338 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1339 RTLFn =
1340 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1341 break;
1342 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001343 case OMPRTL__kmpc_omp_task_begin_if0: {
1344 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1345 // *new_task);
1346 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1347 CGM.VoidPtrTy};
1348 llvm::FunctionType *FnTy =
1349 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1350 RTLFn =
1351 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1352 break;
1353 }
1354 case OMPRTL__kmpc_omp_task_complete_if0: {
1355 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1356 // *new_task);
1357 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1358 CGM.VoidPtrTy};
1359 llvm::FunctionType *FnTy =
1360 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1361 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1362 /*Name=*/"__kmpc_omp_task_complete_if0");
1363 break;
1364 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001365 case OMPRTL__kmpc_ordered: {
1366 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1367 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1368 llvm::FunctionType *FnTy =
1369 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1370 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1371 break;
1372 }
1373 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001374 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001375 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1376 llvm::FunctionType *FnTy =
1377 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1378 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1379 break;
1380 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001381 case OMPRTL__kmpc_omp_taskwait: {
1382 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1383 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1384 llvm::FunctionType *FnTy =
1385 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1386 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1387 break;
1388 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001389 case OMPRTL__kmpc_taskgroup: {
1390 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1391 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1392 llvm::FunctionType *FnTy =
1393 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1394 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1395 break;
1396 }
1397 case OMPRTL__kmpc_end_taskgroup: {
1398 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1399 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1400 llvm::FunctionType *FnTy =
1401 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1402 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1403 break;
1404 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001405 case OMPRTL__kmpc_push_proc_bind: {
1406 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1407 // int proc_bind)
1408 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1409 llvm::FunctionType *FnTy =
1410 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1411 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1412 break;
1413 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001414 case OMPRTL__kmpc_omp_task_with_deps: {
1415 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1416 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1417 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1418 llvm::Type *TypeParams[] = {
1419 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1420 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1421 llvm::FunctionType *FnTy =
1422 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1423 RTLFn =
1424 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1425 break;
1426 }
1427 case OMPRTL__kmpc_omp_wait_deps: {
1428 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1429 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1430 // kmp_depend_info_t *noalias_dep_list);
1431 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1432 CGM.Int32Ty, CGM.VoidPtrTy,
1433 CGM.Int32Ty, CGM.VoidPtrTy};
1434 llvm::FunctionType *FnTy =
1435 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1436 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1437 break;
1438 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001439 case OMPRTL__kmpc_cancellationpoint: {
1440 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1441 // global_tid, kmp_int32 cncl_kind)
1442 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1443 llvm::FunctionType *FnTy =
1444 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1445 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1446 break;
1447 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001448 case OMPRTL__kmpc_cancel: {
1449 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1450 // kmp_int32 cncl_kind)
1451 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1452 llvm::FunctionType *FnTy =
1453 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1454 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1455 break;
1456 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001457 case OMPRTL__kmpc_push_num_teams: {
1458 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1459 // kmp_int32 num_teams, kmp_int32 num_threads)
1460 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1461 CGM.Int32Ty};
1462 llvm::FunctionType *FnTy =
1463 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1464 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1465 break;
1466 }
1467 case OMPRTL__kmpc_fork_teams: {
1468 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1469 // microtask, ...);
1470 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1471 getKmpc_MicroPointerTy()};
1472 llvm::FunctionType *FnTy =
1473 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1474 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1475 break;
1476 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001477 case OMPRTL__kmpc_taskloop: {
1478 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1479 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1480 // sched, kmp_uint64 grainsize, void *task_dup);
1481 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1482 CGM.IntTy,
1483 CGM.VoidPtrTy,
1484 CGM.IntTy,
1485 CGM.Int64Ty->getPointerTo(),
1486 CGM.Int64Ty->getPointerTo(),
1487 CGM.Int64Ty,
1488 CGM.IntTy,
1489 CGM.IntTy,
1490 CGM.Int64Ty,
1491 CGM.VoidPtrTy};
1492 llvm::FunctionType *FnTy =
1493 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1494 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1495 break;
1496 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001497 case OMPRTL__kmpc_doacross_init: {
1498 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1499 // num_dims, struct kmp_dim *dims);
1500 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1501 CGM.Int32Ty,
1502 CGM.Int32Ty,
1503 CGM.VoidPtrTy};
1504 llvm::FunctionType *FnTy =
1505 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1506 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1507 break;
1508 }
1509 case OMPRTL__kmpc_doacross_fini: {
1510 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1511 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1512 llvm::FunctionType *FnTy =
1513 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1514 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1515 break;
1516 }
1517 case OMPRTL__kmpc_doacross_post: {
1518 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1519 // *vec);
1520 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1521 CGM.Int64Ty->getPointerTo()};
1522 llvm::FunctionType *FnTy =
1523 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1524 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1525 break;
1526 }
1527 case OMPRTL__kmpc_doacross_wait: {
1528 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1529 // *vec);
1530 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1531 CGM.Int64Ty->getPointerTo()};
1532 llvm::FunctionType *FnTy =
1533 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1534 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1535 break;
1536 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001537 case OMPRTL__tgt_target: {
1538 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1539 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1540 // *arg_types);
1541 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1542 CGM.VoidPtrTy,
1543 CGM.Int32Ty,
1544 CGM.VoidPtrPtrTy,
1545 CGM.VoidPtrPtrTy,
1546 CGM.SizeTy->getPointerTo(),
1547 CGM.Int32Ty->getPointerTo()};
1548 llvm::FunctionType *FnTy =
1549 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1550 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1551 break;
1552 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001553 case OMPRTL__tgt_target_teams: {
1554 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1555 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1556 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1557 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1558 CGM.VoidPtrTy,
1559 CGM.Int32Ty,
1560 CGM.VoidPtrPtrTy,
1561 CGM.VoidPtrPtrTy,
1562 CGM.SizeTy->getPointerTo(),
1563 CGM.Int32Ty->getPointerTo(),
1564 CGM.Int32Ty,
1565 CGM.Int32Ty};
1566 llvm::FunctionType *FnTy =
1567 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1568 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1569 break;
1570 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001571 case OMPRTL__tgt_register_lib: {
1572 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1573 QualType ParamTy =
1574 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1575 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1576 llvm::FunctionType *FnTy =
1577 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1578 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1579 break;
1580 }
1581 case OMPRTL__tgt_unregister_lib: {
1582 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1583 QualType ParamTy =
1584 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1585 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1586 llvm::FunctionType *FnTy =
1587 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1588 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1589 break;
1590 }
Samuel Antaodf158d52016-04-27 22:58:19 +00001591 case OMPRTL__tgt_target_data_begin: {
1592 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1593 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1594 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1595 CGM.Int32Ty,
1596 CGM.VoidPtrPtrTy,
1597 CGM.VoidPtrPtrTy,
1598 CGM.SizeTy->getPointerTo(),
1599 CGM.Int32Ty->getPointerTo()};
1600 llvm::FunctionType *FnTy =
1601 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1602 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1603 break;
1604 }
1605 case OMPRTL__tgt_target_data_end: {
1606 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1607 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1608 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1609 CGM.Int32Ty,
1610 CGM.VoidPtrPtrTy,
1611 CGM.VoidPtrPtrTy,
1612 CGM.SizeTy->getPointerTo(),
1613 CGM.Int32Ty->getPointerTo()};
1614 llvm::FunctionType *FnTy =
1615 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1616 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1617 break;
1618 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00001619 case OMPRTL__tgt_target_data_update: {
1620 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1621 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1622 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1623 CGM.Int32Ty,
1624 CGM.VoidPtrPtrTy,
1625 CGM.VoidPtrPtrTy,
1626 CGM.SizeTy->getPointerTo(),
1627 CGM.Int32Ty->getPointerTo()};
1628 llvm::FunctionType *FnTy =
1629 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1630 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1631 break;
1632 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001633 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001634 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001635 return RTLFn;
1636}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001637
Alexander Musman21212e42015-03-13 10:38:23 +00001638llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1639 bool IVSigned) {
1640 assert((IVSize == 32 || IVSize == 64) &&
1641 "IV size is not compatible with the omp runtime");
1642 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1643 : "__kmpc_for_static_init_4u")
1644 : (IVSigned ? "__kmpc_for_static_init_8"
1645 : "__kmpc_for_static_init_8u");
1646 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1647 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1648 llvm::Type *TypeParams[] = {
1649 getIdentTyPointerTy(), // loc
1650 CGM.Int32Ty, // tid
1651 CGM.Int32Ty, // schedtype
1652 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1653 PtrTy, // p_lower
1654 PtrTy, // p_upper
1655 PtrTy, // p_stride
1656 ITy, // incr
1657 ITy // chunk
1658 };
1659 llvm::FunctionType *FnTy =
1660 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1661 return CGM.CreateRuntimeFunction(FnTy, Name);
1662}
1663
Alexander Musman92bdaab2015-03-12 13:37:50 +00001664llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1665 bool IVSigned) {
1666 assert((IVSize == 32 || IVSize == 64) &&
1667 "IV size is not compatible with the omp runtime");
1668 auto Name =
1669 IVSize == 32
1670 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1671 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1672 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1673 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1674 CGM.Int32Ty, // tid
1675 CGM.Int32Ty, // schedtype
1676 ITy, // lower
1677 ITy, // upper
1678 ITy, // stride
1679 ITy // chunk
1680 };
1681 llvm::FunctionType *FnTy =
1682 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1683 return CGM.CreateRuntimeFunction(FnTy, Name);
1684}
1685
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001686llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1687 bool IVSigned) {
1688 assert((IVSize == 32 || IVSize == 64) &&
1689 "IV size is not compatible with the omp runtime");
1690 auto Name =
1691 IVSize == 32
1692 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1693 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1694 llvm::Type *TypeParams[] = {
1695 getIdentTyPointerTy(), // loc
1696 CGM.Int32Ty, // tid
1697 };
1698 llvm::FunctionType *FnTy =
1699 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1700 return CGM.CreateRuntimeFunction(FnTy, Name);
1701}
1702
Alexander Musman92bdaab2015-03-12 13:37:50 +00001703llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1704 bool IVSigned) {
1705 assert((IVSize == 32 || IVSize == 64) &&
1706 "IV size is not compatible with the omp runtime");
1707 auto Name =
1708 IVSize == 32
1709 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1710 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1711 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1712 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1713 llvm::Type *TypeParams[] = {
1714 getIdentTyPointerTy(), // loc
1715 CGM.Int32Ty, // tid
1716 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1717 PtrTy, // p_lower
1718 PtrTy, // p_upper
1719 PtrTy // p_stride
1720 };
1721 llvm::FunctionType *FnTy =
1722 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1723 return CGM.CreateRuntimeFunction(FnTy, Name);
1724}
1725
Alexey Bataev97720002014-11-11 04:05:39 +00001726llvm::Constant *
1727CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001728 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1729 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001730 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001731 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001732 Twine(CGM.getMangledName(VD)) + ".cache.");
1733}
1734
John McCall7f416cc2015-09-08 08:05:57 +00001735Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1736 const VarDecl *VD,
1737 Address VDAddr,
1738 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001739 if (CGM.getLangOpts().OpenMPUseTLS &&
1740 CGM.getContext().getTargetInfo().isTLSSupported())
1741 return VDAddr;
1742
John McCall7f416cc2015-09-08 08:05:57 +00001743 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001744 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001745 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1746 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001747 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1748 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001749 return Address(CGF.EmitRuntimeCall(
1750 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1751 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001752}
1753
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001754void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001755 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001756 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1757 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1758 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001759 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1760 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001761 OMPLoc);
1762 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1763 // to register constructor/destructor for variable.
1764 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001765 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1766 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001767 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001768 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001769 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001770}
1771
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001772llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001773 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001774 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001775 if (CGM.getLangOpts().OpenMPUseTLS &&
1776 CGM.getContext().getTargetInfo().isTLSSupported())
1777 return nullptr;
1778
Alexey Bataev97720002014-11-11 04:05:39 +00001779 VD = VD->getDefinition(CGM.getContext());
1780 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1781 ThreadPrivateWithDefinition.insert(VD);
1782 QualType ASTTy = VD->getType();
1783
1784 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1785 auto Init = VD->getAnyInitializer();
1786 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1787 // Generate function that re-emits the declaration's initializer into the
1788 // threadprivate copy of the variable VD
1789 CodeGenFunction CtorCGF(CGM);
1790 FunctionArgList Args;
1791 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1792 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1793 Args.push_back(&Dst);
1794
John McCallc56a8b32016-03-11 04:30:31 +00001795 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1796 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001797 auto FTy = CGM.getTypes().GetFunctionType(FI);
1798 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001799 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001800 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1801 Args, SourceLocation());
1802 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001803 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001804 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001805 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1806 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1807 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001808 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1809 /*IsInitializer=*/true);
1810 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001811 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001812 CGM.getContext().VoidPtrTy, Dst.getLocation());
1813 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1814 CtorCGF.FinishFunction();
1815 Ctor = Fn;
1816 }
1817 if (VD->getType().isDestructedType() != QualType::DK_none) {
1818 // Generate function that emits destructor call for the threadprivate copy
1819 // of the variable VD
1820 CodeGenFunction DtorCGF(CGM);
1821 FunctionArgList Args;
1822 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1823 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1824 Args.push_back(&Dst);
1825
John McCallc56a8b32016-03-11 04:30:31 +00001826 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1827 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001828 auto FTy = CGM.getTypes().GetFunctionType(FI);
1829 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001830 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001831 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001832 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1833 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001834 // Create a scope with an artificial location for the body of this function.
1835 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001836 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1837 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001838 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1839 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001840 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1841 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1842 DtorCGF.FinishFunction();
1843 Dtor = Fn;
1844 }
1845 // Do not emit init function if it is not required.
1846 if (!Ctor && !Dtor)
1847 return nullptr;
1848
1849 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1850 auto CopyCtorTy =
1851 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1852 /*isVarArg=*/false)->getPointerTo();
1853 // Copying constructor for the threadprivate variable.
1854 // Must be NULL - reserved by runtime, but currently it requires that this
1855 // parameter is always NULL. Otherwise it fires assertion.
1856 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1857 if (Ctor == nullptr) {
1858 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1859 /*isVarArg=*/false)->getPointerTo();
1860 Ctor = llvm::Constant::getNullValue(CtorTy);
1861 }
1862 if (Dtor == nullptr) {
1863 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1864 /*isVarArg=*/false)->getPointerTo();
1865 Dtor = llvm::Constant::getNullValue(DtorTy);
1866 }
1867 if (!CGF) {
1868 auto InitFunctionTy =
1869 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1870 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001871 InitFunctionTy, ".__omp_threadprivate_init_.",
1872 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001873 CodeGenFunction InitCGF(CGM);
1874 FunctionArgList ArgList;
1875 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1876 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1877 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001878 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001879 InitCGF.FinishFunction();
1880 return InitFunction;
1881 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001882 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001883 }
1884 return nullptr;
1885}
1886
Alexey Bataev1d677132015-04-22 13:57:31 +00001887/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1888/// function. Here is the logic:
1889/// if (Cond) {
1890/// ThenGen();
1891/// } else {
1892/// ElseGen();
1893/// }
1894static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1895 const RegionCodeGenTy &ThenGen,
1896 const RegionCodeGenTy &ElseGen) {
1897 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1898
1899 // If the condition constant folds and can be elided, try to avoid emitting
1900 // the condition and the dead arm of the if/else.
1901 bool CondConstant;
1902 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001903 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001904 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001905 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001906 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001907 return;
1908 }
1909
1910 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1911 // emit the conditional branch.
1912 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1913 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1914 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1915 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1916
1917 // Emit the 'then' code.
1918 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001919 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001920 CGF.EmitBranch(ContBlock);
1921 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001922 // There is no need to emit line number for unconditional branch.
1923 (void)ApplyDebugLocation::CreateEmpty(CGF);
1924 CGF.EmitBlock(ElseBlock);
1925 ElseGen(CGF);
1926 // There is no need to emit line number for unconditional branch.
1927 (void)ApplyDebugLocation::CreateEmpty(CGF);
1928 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001929 // Emit the continuation block for code after the if.
1930 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001931}
1932
Alexey Bataev1d677132015-04-22 13:57:31 +00001933void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1934 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001935 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001936 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001937 if (!CGF.HaveInsertPoint())
1938 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001939 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001940 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1941 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001942 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001943 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001944 llvm::Value *Args[] = {
1945 RTLoc,
1946 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001947 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001948 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1949 RealArgs.append(std::begin(Args), std::end(Args));
1950 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1951
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001952 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001953 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1954 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001955 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1956 PrePostActionTy &) {
1957 auto &RT = CGF.CGM.getOpenMPRuntime();
1958 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001959 // Build calls:
1960 // __kmpc_serialized_parallel(&Loc, GTid);
1961 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001962 CGF.EmitRuntimeCall(
1963 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001964
Alexey Bataev1d677132015-04-22 13:57:31 +00001965 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001966 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001967 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001968 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1969 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001970 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001971 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1972 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1973 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1974 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001975 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001976
Alexey Bataev1d677132015-04-22 13:57:31 +00001977 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001978 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001979 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001980 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1981 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00001982 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001983 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00001984 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001985 else {
1986 RegionCodeGenTy ThenRCG(ThenGen);
1987 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00001988 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001989}
1990
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001991// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001992// thread-ID variable (it is passed in a first argument of the outlined function
1993// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1994// regular serial code region, get thread ID by calling kmp_int32
1995// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1996// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001997Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1998 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001999 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002000 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002001 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002002 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002003
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002004 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002005 auto Int32Ty =
2006 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2007 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2008 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002009 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002010
2011 return ThreadIDTemp;
2012}
2013
Alexey Bataev97720002014-11-11 04:05:39 +00002014llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002015CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002016 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002017 SmallString<256> Buffer;
2018 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002019 Out << Name;
2020 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002021 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2022 if (Elem.second) {
2023 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002024 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002025 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002026 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002027
David Blaikie13156b62014-11-19 03:06:06 +00002028 return Elem.second = new llvm::GlobalVariable(
2029 CGM.getModule(), Ty, /*IsConstant*/ false,
2030 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2031 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002032}
2033
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002034llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002035 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002036 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002037}
2038
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002039namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002040/// Common pre(post)-action for different OpenMP constructs.
2041class CommonActionTy final : public PrePostActionTy {
2042 llvm::Value *EnterCallee;
2043 ArrayRef<llvm::Value *> EnterArgs;
2044 llvm::Value *ExitCallee;
2045 ArrayRef<llvm::Value *> ExitArgs;
2046 bool Conditional;
2047 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002048
2049public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002050 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2051 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2052 bool Conditional = false)
2053 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2054 ExitArgs(ExitArgs), Conditional(Conditional) {}
2055 void Enter(CodeGenFunction &CGF) override {
2056 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2057 if (Conditional) {
2058 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2059 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2060 ContBlock = CGF.createBasicBlock("omp_if.end");
2061 // Generate the branch (If-stmt)
2062 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2063 CGF.EmitBlock(ThenBlock);
2064 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002065 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002066 void Done(CodeGenFunction &CGF) {
2067 // Emit the rest of blocks/branches
2068 CGF.EmitBranch(ContBlock);
2069 CGF.EmitBlock(ContBlock, true);
2070 }
2071 void Exit(CodeGenFunction &CGF) override {
2072 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002073 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002074};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002075} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002076
2077void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2078 StringRef CriticalName,
2079 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002080 SourceLocation Loc, const Expr *Hint) {
2081 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002082 // CriticalOpGen();
2083 // __kmpc_end_critical(ident_t *, gtid, Lock);
2084 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002085 if (!CGF.HaveInsertPoint())
2086 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002087 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2088 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002089 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2090 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002091 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002092 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2093 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2094 }
2095 CommonActionTy Action(
2096 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2097 : OMPRTL__kmpc_critical),
2098 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2099 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002100 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002101}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002102
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002103void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002104 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002105 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002106 if (!CGF.HaveInsertPoint())
2107 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002108 // if(__kmpc_master(ident_t *, gtid)) {
2109 // MasterOpGen();
2110 // __kmpc_end_master(ident_t *, gtid);
2111 // }
2112 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002113 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002114 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2115 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2116 /*Conditional=*/true);
2117 MasterOpGen.setAction(Action);
2118 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2119 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002120}
2121
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002122void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2123 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002124 if (!CGF.HaveInsertPoint())
2125 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002126 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2127 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002128 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002129 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002130 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002131 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2132 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002133}
2134
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002135void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2136 const RegionCodeGenTy &TaskgroupOpGen,
2137 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002138 if (!CGF.HaveInsertPoint())
2139 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002140 // __kmpc_taskgroup(ident_t *, gtid);
2141 // TaskgroupOpGen();
2142 // __kmpc_end_taskgroup(ident_t *, gtid);
2143 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002144 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2145 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2146 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2147 Args);
2148 TaskgroupOpGen.setAction(Action);
2149 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002150}
2151
John McCall7f416cc2015-09-08 08:05:57 +00002152/// Given an array of pointers to variables, project the address of a
2153/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002154static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2155 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002156 // Pull out the pointer to the variable.
2157 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002158 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002159 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2160
2161 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002162 Addr = CGF.Builder.CreateElementBitCast(
2163 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002164 return Addr;
2165}
2166
Alexey Bataeva63048e2015-03-23 06:18:07 +00002167static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002168 CodeGenModule &CGM, llvm::Type *ArgsType,
2169 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2170 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002171 auto &C = CGM.getContext();
2172 // void copy_func(void *LHSArg, void *RHSArg);
2173 FunctionArgList Args;
2174 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2175 C.VoidPtrTy);
2176 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2177 C.VoidPtrTy);
2178 Args.push_back(&LHSArg);
2179 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002180 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002181 auto *Fn = llvm::Function::Create(
2182 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2183 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002184 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002185 CodeGenFunction CGF(CGM);
2186 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002187 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002188 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002189 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2190 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2191 ArgsType), CGF.getPointerAlign());
2192 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2193 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2194 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002195 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2196 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2197 // ...
2198 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002199 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002200 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2201 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2202
2203 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2204 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2205
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002206 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2207 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002208 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002209 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002210 CGF.FinishFunction();
2211 return Fn;
2212}
2213
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002214void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002215 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002216 SourceLocation Loc,
2217 ArrayRef<const Expr *> CopyprivateVars,
2218 ArrayRef<const Expr *> SrcExprs,
2219 ArrayRef<const Expr *> DstExprs,
2220 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002221 if (!CGF.HaveInsertPoint())
2222 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002223 assert(CopyprivateVars.size() == SrcExprs.size() &&
2224 CopyprivateVars.size() == DstExprs.size() &&
2225 CopyprivateVars.size() == AssignmentOps.size());
2226 auto &C = CGM.getContext();
2227 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002228 // if(__kmpc_single(ident_t *, gtid)) {
2229 // SingleOpGen();
2230 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002231 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002232 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002233 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2234 // <copy_func>, did_it);
2235
John McCall7f416cc2015-09-08 08:05:57 +00002236 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002237 if (!CopyprivateVars.empty()) {
2238 // int32 did_it = 0;
2239 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2240 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002241 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002242 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002243 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002244 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002245 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2246 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2247 /*Conditional=*/true);
2248 SingleOpGen.setAction(Action);
2249 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2250 if (DidIt.isValid()) {
2251 // did_it = 1;
2252 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2253 }
2254 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002255 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2256 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002257 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002258 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2259 auto CopyprivateArrayTy =
2260 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2261 /*IndexTypeQuals=*/0);
2262 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002263 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002264 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2265 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002266 Address Elem = CGF.Builder.CreateConstArrayGEP(
2267 CopyprivateList, I, CGF.getPointerSize());
2268 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002269 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002270 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2271 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002272 }
2273 // Build function that copies private values from single region to all other
2274 // threads in the corresponding parallel region.
2275 auto *CpyFn = emitCopyprivateCopyFunction(
2276 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002277 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002278 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002279 Address CL =
2280 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2281 CGF.VoidPtrTy);
2282 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002283 llvm::Value *Args[] = {
2284 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2285 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002286 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002287 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002288 CpyFn, // void (*) (void *, void *) <copy_func>
2289 DidItVal // i32 did_it
2290 };
2291 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2292 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002293}
2294
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002295void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2296 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002297 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002298 if (!CGF.HaveInsertPoint())
2299 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002300 // __kmpc_ordered(ident_t *, gtid);
2301 // OrderedOpGen();
2302 // __kmpc_end_ordered(ident_t *, gtid);
2303 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002304 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002305 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002306 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2307 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2308 Args);
2309 OrderedOpGen.setAction(Action);
2310 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2311 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002312 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002313 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002314}
2315
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002316void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002317 OpenMPDirectiveKind Kind, bool EmitChecks,
2318 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002319 if (!CGF.HaveInsertPoint())
2320 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002321 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002322 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002323 unsigned Flags;
2324 if (Kind == OMPD_for)
2325 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2326 else if (Kind == OMPD_sections)
2327 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2328 else if (Kind == OMPD_single)
2329 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2330 else if (Kind == OMPD_barrier)
2331 Flags = OMP_IDENT_BARRIER_EXPL;
2332 else
2333 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002334 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2335 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002336 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2337 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002338 if (auto *OMPRegionInfo =
2339 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002340 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002341 auto *Result = CGF.EmitRuntimeCall(
2342 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002343 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002344 // if (__kmpc_cancel_barrier()) {
2345 // exit from construct;
2346 // }
2347 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2348 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2349 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2350 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2351 CGF.EmitBlock(ExitBB);
2352 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002353 auto CancelDestination =
2354 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002355 CGF.EmitBranchThroughCleanup(CancelDestination);
2356 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2357 }
2358 return;
2359 }
2360 }
2361 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002362}
2363
Alexander Musmanc6388682014-12-15 07:07:06 +00002364/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2365static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002366 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002367 switch (ScheduleKind) {
2368 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002369 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2370 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002371 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002372 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002373 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002374 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002375 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002376 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2377 case OMPC_SCHEDULE_auto:
2378 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002379 case OMPC_SCHEDULE_unknown:
2380 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002381 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002382 }
2383 llvm_unreachable("Unexpected runtime schedule");
2384}
2385
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002386/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2387static OpenMPSchedType
2388getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2389 // only static is allowed for dist_schedule
2390 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2391}
2392
Alexander Musmanc6388682014-12-15 07:07:06 +00002393bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2394 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002395 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002396 return Schedule == OMP_sch_static;
2397}
2398
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002399bool CGOpenMPRuntime::isStaticNonchunked(
2400 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2401 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2402 return Schedule == OMP_dist_sch_static;
2403}
2404
2405
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002406bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002407 auto Schedule =
2408 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002409 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2410 return Schedule != OMP_sch_static;
2411}
2412
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002413static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2414 OpenMPScheduleClauseModifier M1,
2415 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002416 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002417 switch (M1) {
2418 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002419 Modifier = OMP_sch_modifier_monotonic;
2420 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002421 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002422 Modifier = OMP_sch_modifier_nonmonotonic;
2423 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002424 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002425 if (Schedule == OMP_sch_static_chunked)
2426 Schedule = OMP_sch_static_balanced_chunked;
2427 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002428 case OMPC_SCHEDULE_MODIFIER_last:
2429 case OMPC_SCHEDULE_MODIFIER_unknown:
2430 break;
2431 }
2432 switch (M2) {
2433 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002434 Modifier = OMP_sch_modifier_monotonic;
2435 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002436 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002437 Modifier = OMP_sch_modifier_nonmonotonic;
2438 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002439 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002440 if (Schedule == OMP_sch_static_chunked)
2441 Schedule = OMP_sch_static_balanced_chunked;
2442 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002443 case OMPC_SCHEDULE_MODIFIER_last:
2444 case OMPC_SCHEDULE_MODIFIER_unknown:
2445 break;
2446 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002447 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002448}
2449
John McCall7f416cc2015-09-08 08:05:57 +00002450void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2451 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002452 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002453 unsigned IVSize, bool IVSigned,
2454 bool Ordered, llvm::Value *UB,
2455 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002456 if (!CGF.HaveInsertPoint())
2457 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002458 OpenMPSchedType Schedule =
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002459 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002460 assert(Ordered ||
2461 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002462 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2463 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002464 // Call __kmpc_dispatch_init(
2465 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2466 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2467 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002468
John McCall7f416cc2015-09-08 08:05:57 +00002469 // If the Chunk was not specified in the clause - use default value 1.
2470 if (Chunk == nullptr)
2471 Chunk = CGF.Builder.getIntN(IVSize, 1);
2472 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002473 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2474 CGF.Builder.getInt32(addMonoNonMonoModifier(
2475 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2476 CGF.Builder.getIntN(IVSize, 0), // Lower
2477 UB, // Upper
2478 CGF.Builder.getIntN(IVSize, 1), // Stride
2479 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002480 };
2481 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2482}
2483
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002484static void emitForStaticInitCall(
2485 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2486 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2487 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2488 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2489 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002490 if (!CGF.HaveInsertPoint())
2491 return;
2492
2493 assert(!Ordered);
2494 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002495 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002496 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2497 Schedule == OMP_dist_sch_static ||
2498 Schedule == OMP_dist_sch_static_chunked);
2499
2500 // Call __kmpc_for_static_init(
2501 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2502 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2503 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2504 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2505 if (Chunk == nullptr) {
2506 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2507 Schedule == OMP_dist_sch_static) &&
2508 "expected static non-chunked schedule");
2509 // If the Chunk was not specified in the clause - use default value 1.
2510 Chunk = CGF.Builder.getIntN(IVSize, 1);
2511 } else {
2512 assert((Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002513 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002514 Schedule == OMP_ord_static_chunked ||
2515 Schedule == OMP_dist_sch_static_chunked) &&
2516 "expected static chunked schedule");
2517 }
2518 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002519 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2520 Schedule, M1, M2)), // Schedule type
2521 IL.getPointer(), // &isLastIter
2522 LB.getPointer(), // &LB
2523 UB.getPointer(), // &UB
2524 ST.getPointer(), // &Stride
2525 CGF.Builder.getIntN(IVSize, 1), // Incr
2526 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002527 };
2528 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2529}
2530
John McCall7f416cc2015-09-08 08:05:57 +00002531void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2532 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002533 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002534 unsigned IVSize, bool IVSigned,
2535 bool Ordered, Address IL, Address LB,
2536 Address UB, Address ST,
2537 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002538 OpenMPSchedType ScheduleNum =
2539 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002540 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2541 auto *ThreadId = getThreadID(CGF, Loc);
2542 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002543 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2544 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2545 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002546}
John McCall7f416cc2015-09-08 08:05:57 +00002547
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002548void CGOpenMPRuntime::emitDistributeStaticInit(
2549 CodeGenFunction &CGF, SourceLocation Loc,
2550 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2551 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002552 llvm::Value *Chunk) {
2553 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2554 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2555 auto *ThreadId = getThreadID(CGF, Loc);
2556 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002557 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2558 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2559 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2560 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002561}
2562
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002563void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2564 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002565 if (!CGF.HaveInsertPoint())
2566 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002567 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002568 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002569 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2570 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002571}
2572
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002573void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2574 SourceLocation Loc,
2575 unsigned IVSize,
2576 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002577 if (!CGF.HaveInsertPoint())
2578 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002579 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002580 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002581 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2582}
2583
Alexander Musman92bdaab2015-03-12 13:37:50 +00002584llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2585 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002586 bool IVSigned, Address IL,
2587 Address LB, Address UB,
2588 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002589 // Call __kmpc_dispatch_next(
2590 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2591 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2592 // kmp_int[32|64] *p_stride);
2593 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002594 emitUpdateLocation(CGF, Loc),
2595 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002596 IL.getPointer(), // &isLastIter
2597 LB.getPointer(), // &Lower
2598 UB.getPointer(), // &Upper
2599 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002600 };
2601 llvm::Value *Call =
2602 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2603 return CGF.EmitScalarConversion(
2604 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002605 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002606}
2607
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002608void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2609 llvm::Value *NumThreads,
2610 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002611 if (!CGF.HaveInsertPoint())
2612 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002613 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2614 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002615 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002616 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002617 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2618 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002619}
2620
Alexey Bataev7f210c62015-06-18 13:40:03 +00002621void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2622 OpenMPProcBindClauseKind ProcBind,
2623 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002624 if (!CGF.HaveInsertPoint())
2625 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002626 // Constants for proc bind value accepted by the runtime.
2627 enum ProcBindTy {
2628 ProcBindFalse = 0,
2629 ProcBindTrue,
2630 ProcBindMaster,
2631 ProcBindClose,
2632 ProcBindSpread,
2633 ProcBindIntel,
2634 ProcBindDefault
2635 } RuntimeProcBind;
2636 switch (ProcBind) {
2637 case OMPC_PROC_BIND_master:
2638 RuntimeProcBind = ProcBindMaster;
2639 break;
2640 case OMPC_PROC_BIND_close:
2641 RuntimeProcBind = ProcBindClose;
2642 break;
2643 case OMPC_PROC_BIND_spread:
2644 RuntimeProcBind = ProcBindSpread;
2645 break;
2646 case OMPC_PROC_BIND_unknown:
2647 llvm_unreachable("Unsupported proc_bind value.");
2648 }
2649 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2650 llvm::Value *Args[] = {
2651 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2652 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2653 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2654}
2655
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002656void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2657 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002658 if (!CGF.HaveInsertPoint())
2659 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002660 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002661 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2662 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002663}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002664
Alexey Bataev62b63b12015-03-10 07:28:44 +00002665namespace {
2666/// \brief Indexes of fields for type kmp_task_t.
2667enum KmpTaskTFields {
2668 /// \brief List of shared variables.
2669 KmpTaskTShareds,
2670 /// \brief Task routine.
2671 KmpTaskTRoutine,
2672 /// \brief Partition id for the untied tasks.
2673 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00002674 /// Function with call of destructors for private variables.
2675 Data1,
2676 /// Task priority.
2677 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00002678 /// (Taskloops only) Lower bound.
2679 KmpTaskTLowerBound,
2680 /// (Taskloops only) Upper bound.
2681 KmpTaskTUpperBound,
2682 /// (Taskloops only) Stride.
2683 KmpTaskTStride,
2684 /// (Taskloops only) Is last iteration flag.
2685 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002686};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002687} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002688
Samuel Antaoee8fb302016-01-06 13:42:12 +00002689bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2690 // FIXME: Add other entries type when they become supported.
2691 return OffloadEntriesTargetRegion.empty();
2692}
2693
2694/// \brief Initialize target region entry.
2695void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2696 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2697 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002698 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002699 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2700 "only required for the device "
2701 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002702 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002703 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2704 ++OffloadingEntriesNum;
2705}
2706
2707void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2708 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2709 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002710 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002711 // If we are emitting code for a target, the entry is already initialized,
2712 // only has to be registered.
2713 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002714 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002715 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002716 auto &Entry =
2717 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002718 assert(Entry.isValid() && "Entry not initialized!");
2719 Entry.setAddress(Addr);
2720 Entry.setID(ID);
2721 return;
2722 } else {
2723 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002724 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002725 }
2726}
2727
2728bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002729 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2730 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002731 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2732 if (PerDevice == OffloadEntriesTargetRegion.end())
2733 return false;
2734 auto PerFile = PerDevice->second.find(FileID);
2735 if (PerFile == PerDevice->second.end())
2736 return false;
2737 auto PerParentName = PerFile->second.find(ParentName);
2738 if (PerParentName == PerFile->second.end())
2739 return false;
2740 auto PerLine = PerParentName->second.find(LineNum);
2741 if (PerLine == PerParentName->second.end())
2742 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002743 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002744 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002745 return false;
2746 return true;
2747}
2748
2749void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2750 const OffloadTargetRegionEntryInfoActTy &Action) {
2751 // Scan all target region entries and perform the provided action.
2752 for (auto &D : OffloadEntriesTargetRegion)
2753 for (auto &F : D.second)
2754 for (auto &P : F.second)
2755 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002756 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002757}
2758
2759/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2760/// \a Codegen. This is used to emit the two functions that register and
2761/// unregister the descriptor of the current compilation unit.
2762static llvm::Function *
2763createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2764 const RegionCodeGenTy &Codegen) {
2765 auto &C = CGM.getContext();
2766 FunctionArgList Args;
2767 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2768 /*Id=*/nullptr, C.VoidPtrTy);
2769 Args.push_back(&DummyPtr);
2770
2771 CodeGenFunction CGF(CGM);
2772 GlobalDecl();
John McCallc56a8b32016-03-11 04:30:31 +00002773 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002774 auto FTy = CGM.getTypes().GetFunctionType(FI);
2775 auto *Fn =
2776 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2777 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2778 Codegen(CGF);
2779 CGF.FinishFunction();
2780 return Fn;
2781}
2782
2783llvm::Function *
2784CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2785
2786 // If we don't have entries or if we are emitting code for the device, we
2787 // don't need to do anything.
2788 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2789 return nullptr;
2790
2791 auto &M = CGM.getModule();
2792 auto &C = CGM.getContext();
2793
2794 // Get list of devices we care about
2795 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2796
2797 // We should be creating an offloading descriptor only if there are devices
2798 // specified.
2799 assert(!Devices.empty() && "No OpenMP offloading devices??");
2800
2801 // Create the external variables that will point to the begin and end of the
2802 // host entries section. These will be defined by the linker.
2803 auto *OffloadEntryTy =
2804 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2805 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2806 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002807 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002808 ".omp_offloading.entries_begin");
2809 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2810 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002811 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002812 ".omp_offloading.entries_end");
2813
2814 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00002815 auto *DeviceImageTy = cast<llvm::StructType>(
2816 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002817 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002818 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002819
2820 for (unsigned i = 0; i < Devices.size(); ++i) {
2821 StringRef T = Devices[i].getTriple();
2822 auto *ImgBegin = new llvm::GlobalVariable(
2823 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002824 /*Initializer=*/nullptr,
2825 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002826 auto *ImgEnd = new llvm::GlobalVariable(
2827 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002828 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002829
John McCall6c9f1fdb2016-11-19 08:17:24 +00002830 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2831 Dev.add(ImgBegin);
2832 Dev.add(ImgEnd);
2833 Dev.add(HostEntriesBegin);
2834 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00002835 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002836 }
2837
2838 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002839 llvm::GlobalVariable *DeviceImages =
2840 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2841 CGM.getPointerAlign(),
2842 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002843 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002844
2845 // This is a Zero array to be used in the creation of the constant expressions
2846 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2847 llvm::Constant::getNullValue(CGM.Int32Ty)};
2848
2849 // Create the target region descriptor.
2850 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2851 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002852 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002853 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2854 DescInit.addInt(CGM.Int32Ty, Devices.size());
2855 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2856 DeviceImages,
2857 Index));
2858 DescInit.add(HostEntriesBegin);
2859 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002860
John McCall6c9f1fdb2016-11-19 08:17:24 +00002861 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2862 CGM.getPointerAlign(),
2863 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002864
2865 // Emit code to register or unregister the descriptor at execution
2866 // startup or closing, respectively.
2867
2868 // Create a variable to drive the registration and unregistration of the
2869 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2870 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2871 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2872 IdentInfo, C.CharTy);
2873
2874 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002875 CGM, ".omp_offloading.descriptor_unreg",
2876 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002877 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2878 Desc);
2879 });
2880 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002881 CGM, ".omp_offloading.descriptor_reg",
2882 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002883 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2884 Desc);
2885 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2886 });
2887 return RegFn;
2888}
2889
Samuel Antao2de62b02016-02-13 23:35:10 +00002890void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2891 llvm::Constant *Addr, uint64_t Size) {
2892 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002893 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2894 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2895 llvm::LLVMContext &C = CGM.getModule().getContext();
2896 llvm::Module &M = CGM.getModule();
2897
2898 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002899 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002900
2901 // Create constant string with the name.
2902 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2903
2904 llvm::GlobalVariable *Str =
2905 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2906 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2907 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002908 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002909 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2910
John McCall6c9f1fdb2016-11-19 08:17:24 +00002911 // We can't have any padding between symbols, so we need to have 1-byte
2912 // alignment.
2913 auto Align = CharUnits::fromQuantity(1);
2914
Samuel Antaoee8fb302016-01-06 13:42:12 +00002915 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00002916 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002917 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2918 EntryInit.add(AddrPtr);
2919 EntryInit.add(StrPtr);
2920 EntryInit.addInt(CGM.SizeTy, Size);
2921 llvm::GlobalVariable *Entry =
2922 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2923 Align,
2924 /*constant*/ true,
2925 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002926
2927 // The entry has to be created in the section the linker expects it to be.
2928 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00002929}
2930
2931void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2932 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00002933 // can easily figure out what to emit. The produced metadata looks like
2934 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00002935 //
2936 // !omp_offload.info = !{!1, ...}
2937 //
2938 // Right now we only generate metadata for function that contain target
2939 // regions.
2940
2941 // If we do not have entries, we dont need to do anything.
2942 if (OffloadEntriesInfoManager.empty())
2943 return;
2944
2945 llvm::Module &M = CGM.getModule();
2946 llvm::LLVMContext &C = M.getContext();
2947 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2948 OrderedEntries(OffloadEntriesInfoManager.size());
2949
2950 // Create the offloading info metadata node.
2951 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2952
2953 // Auxiliar methods to create metadata values and strings.
2954 auto getMDInt = [&](unsigned v) {
2955 return llvm::ConstantAsMetadata::get(
2956 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2957 };
2958
2959 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2960
2961 // Create function that emits metadata for each target region entry;
2962 auto &&TargetRegionMetadataEmitter = [&](
2963 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002964 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2965 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2966 // Generate metadata for target regions. Each entry of this metadata
2967 // contains:
2968 // - Entry 0 -> Kind of this type of metadata (0).
2969 // - Entry 1 -> Device ID of the file where the entry was identified.
2970 // - Entry 2 -> File ID of the file where the entry was identified.
2971 // - Entry 3 -> Mangled name of the function where the entry was identified.
2972 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002973 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002974 // The first element of the metadata node is the kind.
2975 Ops.push_back(getMDInt(E.getKind()));
2976 Ops.push_back(getMDInt(DeviceID));
2977 Ops.push_back(getMDInt(FileID));
2978 Ops.push_back(getMDString(ParentName));
2979 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002980 Ops.push_back(getMDInt(E.getOrder()));
2981
2982 // Save this entry in the right position of the ordered entries array.
2983 OrderedEntries[E.getOrder()] = &E;
2984
2985 // Add metadata to the named metadata node.
2986 MD->addOperand(llvm::MDNode::get(C, Ops));
2987 };
2988
2989 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2990 TargetRegionMetadataEmitter);
2991
2992 for (auto *E : OrderedEntries) {
2993 assert(E && "All ordered entries must exist!");
2994 if (auto *CE =
2995 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2996 E)) {
2997 assert(CE->getID() && CE->getAddress() &&
2998 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002999 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003000 } else
3001 llvm_unreachable("Unsupported entry kind.");
3002 }
3003}
3004
3005/// \brief Loads all the offload entries information from the host IR
3006/// metadata.
3007void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3008 // If we are in target mode, load the metadata from the host IR. This code has
3009 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3010
3011 if (!CGM.getLangOpts().OpenMPIsDevice)
3012 return;
3013
3014 if (CGM.getLangOpts().OMPHostIRFile.empty())
3015 return;
3016
3017 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3018 if (Buf.getError())
3019 return;
3020
3021 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003022 auto ME = expectedToErrorOrAndEmitErrors(
3023 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003024
3025 if (ME.getError())
3026 return;
3027
3028 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3029 if (!MD)
3030 return;
3031
3032 for (auto I : MD->operands()) {
3033 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3034
3035 auto getMDInt = [&](unsigned Idx) {
3036 llvm::ConstantAsMetadata *V =
3037 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3038 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3039 };
3040
3041 auto getMDString = [&](unsigned Idx) {
3042 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3043 return V->getString();
3044 };
3045
3046 switch (getMDInt(0)) {
3047 default:
3048 llvm_unreachable("Unexpected metadata!");
3049 break;
3050 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3051 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3052 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3053 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3054 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003055 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003056 break;
3057 }
3058 }
3059}
3060
Alexey Bataev62b63b12015-03-10 07:28:44 +00003061void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3062 if (!KmpRoutineEntryPtrTy) {
3063 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3064 auto &C = CGM.getContext();
3065 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3066 FunctionProtoType::ExtProtoInfo EPI;
3067 KmpRoutineEntryPtrQTy = C.getPointerType(
3068 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3069 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3070 }
3071}
3072
Alexey Bataevc71a4092015-09-11 10:29:41 +00003073static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3074 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003075 auto *Field = FieldDecl::Create(
3076 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3077 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3078 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3079 Field->setAccess(AS_public);
3080 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003081 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003082}
3083
Samuel Antaoee8fb302016-01-06 13:42:12 +00003084QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3085
3086 // Make sure the type of the entry is already created. This is the type we
3087 // have to create:
3088 // struct __tgt_offload_entry{
3089 // void *addr; // Pointer to the offload entry info.
3090 // // (function or global)
3091 // char *name; // Name of the function or global.
3092 // size_t size; // Size of the entry info (0 if it a function).
3093 // };
3094 if (TgtOffloadEntryQTy.isNull()) {
3095 ASTContext &C = CGM.getContext();
3096 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3097 RD->startDefinition();
3098 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3099 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3100 addFieldToRecordDecl(C, RD, C.getSizeType());
3101 RD->completeDefinition();
3102 TgtOffloadEntryQTy = C.getRecordType(RD);
3103 }
3104 return TgtOffloadEntryQTy;
3105}
3106
3107QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3108 // These are the types we need to build:
3109 // struct __tgt_device_image{
3110 // void *ImageStart; // Pointer to the target code start.
3111 // void *ImageEnd; // Pointer to the target code end.
3112 // // We also add the host entries to the device image, as it may be useful
3113 // // for the target runtime to have access to that information.
3114 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3115 // // the entries.
3116 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3117 // // entries (non inclusive).
3118 // };
3119 if (TgtDeviceImageQTy.isNull()) {
3120 ASTContext &C = CGM.getContext();
3121 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3122 RD->startDefinition();
3123 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3124 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3125 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3126 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3127 RD->completeDefinition();
3128 TgtDeviceImageQTy = C.getRecordType(RD);
3129 }
3130 return TgtDeviceImageQTy;
3131}
3132
3133QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3134 // struct __tgt_bin_desc{
3135 // int32_t NumDevices; // Number of devices supported.
3136 // __tgt_device_image *DeviceImages; // Arrays of device images
3137 // // (one per device).
3138 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3139 // // entries.
3140 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3141 // // entries (non inclusive).
3142 // };
3143 if (TgtBinaryDescriptorQTy.isNull()) {
3144 ASTContext &C = CGM.getContext();
3145 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3146 RD->startDefinition();
3147 addFieldToRecordDecl(
3148 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3149 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3150 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3151 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3152 RD->completeDefinition();
3153 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3154 }
3155 return TgtBinaryDescriptorQTy;
3156}
3157
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003158namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003159struct PrivateHelpersTy {
3160 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3161 const VarDecl *PrivateElemInit)
3162 : Original(Original), PrivateCopy(PrivateCopy),
3163 PrivateElemInit(PrivateElemInit) {}
3164 const VarDecl *Original;
3165 const VarDecl *PrivateCopy;
3166 const VarDecl *PrivateElemInit;
3167};
3168typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003169} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003170
Alexey Bataev9e034042015-05-05 04:05:12 +00003171static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003172createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003173 if (!Privates.empty()) {
3174 auto &C = CGM.getContext();
3175 // Build struct .kmp_privates_t. {
3176 // /* private vars */
3177 // };
3178 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3179 RD->startDefinition();
3180 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003181 auto *VD = Pair.second.Original;
3182 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003183 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003184 auto *FD = addFieldToRecordDecl(C, RD, Type);
3185 if (VD->hasAttrs()) {
3186 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3187 E(VD->getAttrs().end());
3188 I != E; ++I)
3189 FD->addAttr(*I);
3190 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003191 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003192 RD->completeDefinition();
3193 return RD;
3194 }
3195 return nullptr;
3196}
3197
Alexey Bataev9e034042015-05-05 04:05:12 +00003198static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003199createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3200 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003201 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003202 auto &C = CGM.getContext();
3203 // Build struct kmp_task_t {
3204 // void * shareds;
3205 // kmp_routine_entry_t routine;
3206 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003207 // kmp_cmplrdata_t data1;
3208 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003209 // For taskloops additional fields:
3210 // kmp_uint64 lb;
3211 // kmp_uint64 ub;
3212 // kmp_int64 st;
3213 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003214 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003215 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3216 UD->startDefinition();
3217 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3218 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3219 UD->completeDefinition();
3220 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003221 auto *RD = C.buildImplicitRecord("kmp_task_t");
3222 RD->startDefinition();
3223 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3224 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3225 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003226 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3227 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003228 if (isOpenMPTaskLoopDirective(Kind)) {
3229 QualType KmpUInt64Ty =
3230 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3231 QualType KmpInt64Ty =
3232 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3233 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3234 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3235 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3236 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3237 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003238 RD->completeDefinition();
3239 return RD;
3240}
3241
3242static RecordDecl *
3243createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003244 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003245 auto &C = CGM.getContext();
3246 // Build struct kmp_task_t_with_privates {
3247 // kmp_task_t task_data;
3248 // .kmp_privates_t. privates;
3249 // };
3250 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3251 RD->startDefinition();
3252 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003253 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3254 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3255 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003256 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003257 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003258}
3259
3260/// \brief Emit a proxy function which accepts kmp_task_t as the second
3261/// argument.
3262/// \code
3263/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003264/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003265/// For taskloops:
3266/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003267/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003268/// return 0;
3269/// }
3270/// \endcode
3271static llvm::Value *
3272emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003273 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3274 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003275 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003276 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3277 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003278 auto &C = CGM.getContext();
3279 FunctionArgList Args;
3280 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3281 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003282 /*Id=*/nullptr,
3283 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003284 Args.push_back(&GtidArg);
3285 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003286 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003287 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003288 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3289 auto *TaskEntry =
3290 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3291 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003292 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003293 CodeGenFunction CGF(CGM);
3294 CGF.disableDebugInfo();
3295 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3296
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003297 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003298 // tt,
3299 // For taskloops:
3300 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3301 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003302 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003303 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003304 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3305 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3306 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003307 auto *KmpTaskTWithPrivatesQTyRD =
3308 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003309 LValue Base =
3310 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003311 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3312 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3313 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003314 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003315
3316 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3317 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003318 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003319 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003320 CGF.ConvertTypeForMem(SharedsPtrTy));
3321
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003322 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3323 llvm::Value *PrivatesParam;
3324 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3325 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3326 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003327 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003328 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003329 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003330
Alexey Bataev7292c292016-04-25 12:22:29 +00003331 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3332 TaskPrivatesMap,
3333 CGF.Builder
3334 .CreatePointerBitCastOrAddrSpaceCast(
3335 TDBase.getAddress(), CGF.VoidPtrTy)
3336 .getPointer()};
3337 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3338 std::end(CommonArgs));
3339 if (isOpenMPTaskLoopDirective(Kind)) {
3340 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3341 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3342 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3343 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3344 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3345 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3346 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3347 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3348 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3349 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3350 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3351 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3352 CallArgs.push_back(LBParam);
3353 CallArgs.push_back(UBParam);
3354 CallArgs.push_back(StParam);
3355 CallArgs.push_back(LIParam);
3356 }
3357 CallArgs.push_back(SharedsParam);
3358
Alexey Bataev62b63b12015-03-10 07:28:44 +00003359 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3360 CGF.EmitStoreThroughLValue(
3361 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003362 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003363 CGF.FinishFunction();
3364 return TaskEntry;
3365}
3366
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003367static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3368 SourceLocation Loc,
3369 QualType KmpInt32Ty,
3370 QualType KmpTaskTWithPrivatesPtrQTy,
3371 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003372 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003373 FunctionArgList Args;
3374 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3375 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003376 /*Id=*/nullptr,
3377 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003378 Args.push_back(&GtidArg);
3379 Args.push_back(&TaskTypeArg);
3380 FunctionType::ExtInfo Info;
3381 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003382 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003383 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3384 auto *DestructorFn =
3385 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3386 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003387 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3388 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003389 CodeGenFunction CGF(CGM);
3390 CGF.disableDebugInfo();
3391 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3392 Args);
3393
Alexey Bataev31300ed2016-02-04 11:27:03 +00003394 LValue Base = CGF.EmitLoadOfPointerLValue(
3395 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3396 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003397 auto *KmpTaskTWithPrivatesQTyRD =
3398 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3399 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003400 Base = CGF.EmitLValueForField(Base, *FI);
3401 for (auto *Field :
3402 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3403 if (auto DtorKind = Field->getType().isDestructedType()) {
3404 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3405 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3406 }
3407 }
3408 CGF.FinishFunction();
3409 return DestructorFn;
3410}
3411
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003412/// \brief Emit a privates mapping function for correct handling of private and
3413/// firstprivate variables.
3414/// \code
3415/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3416/// **noalias priv1,..., <tyn> **noalias privn) {
3417/// *priv1 = &.privates.priv1;
3418/// ...;
3419/// *privn = &.privates.privn;
3420/// }
3421/// \endcode
3422static llvm::Value *
3423emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003424 ArrayRef<const Expr *> PrivateVars,
3425 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003426 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003427 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003428 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003429 auto &C = CGM.getContext();
3430 FunctionArgList Args;
3431 ImplicitParamDecl TaskPrivatesArg(
3432 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3433 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3434 Args.push_back(&TaskPrivatesArg);
3435 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3436 unsigned Counter = 1;
3437 for (auto *E: PrivateVars) {
3438 Args.push_back(ImplicitParamDecl::Create(
3439 C, /*DC=*/nullptr, Loc,
3440 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3441 .withConst()
3442 .withRestrict()));
3443 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3444 PrivateVarsPos[VD] = Counter;
3445 ++Counter;
3446 }
3447 for (auto *E : FirstprivateVars) {
3448 Args.push_back(ImplicitParamDecl::Create(
3449 C, /*DC=*/nullptr, Loc,
3450 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3451 .withConst()
3452 .withRestrict()));
3453 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3454 PrivateVarsPos[VD] = Counter;
3455 ++Counter;
3456 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003457 for (auto *E: LastprivateVars) {
3458 Args.push_back(ImplicitParamDecl::Create(
3459 C, /*DC=*/nullptr, Loc,
3460 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3461 .withConst()
3462 .withRestrict()));
3463 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3464 PrivateVarsPos[VD] = Counter;
3465 ++Counter;
3466 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003467 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003468 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003469 auto *TaskPrivatesMapTy =
3470 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3471 auto *TaskPrivatesMap = llvm::Function::Create(
3472 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3473 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003474 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3475 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003476 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003477 CodeGenFunction CGF(CGM);
3478 CGF.disableDebugInfo();
3479 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3480 TaskPrivatesMapFnInfo, Args);
3481
3482 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003483 LValue Base = CGF.EmitLoadOfPointerLValue(
3484 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3485 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003486 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3487 Counter = 0;
3488 for (auto *Field : PrivatesQTyRD->fields()) {
3489 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3490 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003491 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003492 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3493 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003494 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003495 ++Counter;
3496 }
3497 CGF.FinishFunction();
3498 return TaskPrivatesMap;
3499}
3500
Alexey Bataev9e034042015-05-05 04:05:12 +00003501static int array_pod_sort_comparator(const PrivateDataTy *P1,
3502 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003503 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3504}
3505
Alexey Bataevf93095a2016-05-05 08:46:22 +00003506/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00003507static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003508 const OMPExecutableDirective &D,
3509 Address KmpTaskSharedsPtr, LValue TDBase,
3510 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3511 QualType SharedsTy, QualType SharedsPtrTy,
3512 const OMPTaskDataTy &Data,
3513 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3514 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003515 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3516 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3517 LValue SrcBase;
3518 if (!Data.FirstprivateVars.empty()) {
3519 SrcBase = CGF.MakeAddrLValue(
3520 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3521 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3522 SharedsTy);
3523 }
3524 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3525 cast<CapturedStmt>(*D.getAssociatedStmt()));
3526 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3527 for (auto &&Pair : Privates) {
3528 auto *VD = Pair.second.PrivateCopy;
3529 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003530 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3531 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003532 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003533 if (auto *Elem = Pair.second.PrivateElemInit) {
3534 auto *OriginalVD = Pair.second.Original;
3535 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3536 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3537 SharedRefLValue = CGF.MakeAddrLValue(
3538 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3539 SharedRefLValue.getType(), AlignmentSource::Decl);
3540 QualType Type = OriginalVD->getType();
3541 if (Type->isArrayType()) {
3542 // Initialize firstprivate array.
3543 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3544 // Perform simple memcpy.
3545 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3546 SharedRefLValue.getAddress(), Type);
3547 } else {
3548 // Initialize firstprivate array using element-by-element
3549 // intialization.
3550 CGF.EmitOMPAggregateAssign(
3551 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3552 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3553 Address SrcElement) {
3554 // Clean up any temporaries needed by the initialization.
3555 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3556 InitScope.addPrivate(
3557 Elem, [SrcElement]() -> Address { return SrcElement; });
3558 (void)InitScope.Privatize();
3559 // Emit initialization for single element.
3560 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3561 CGF, &CapturesInfo);
3562 CGF.EmitAnyExprToMem(Init, DestElement,
3563 Init->getType().getQualifiers(),
3564 /*IsInitializer=*/false);
3565 });
3566 }
3567 } else {
3568 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3569 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3570 return SharedRefLValue.getAddress();
3571 });
3572 (void)InitScope.Privatize();
3573 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3574 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3575 /*capturedByInit=*/false);
3576 }
3577 } else
3578 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3579 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003580 ++FI;
3581 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003582}
3583
3584/// Check if duplication function is required for taskloops.
3585static bool checkInitIsRequired(CodeGenFunction &CGF,
3586 ArrayRef<PrivateDataTy> Privates) {
3587 bool InitRequired = false;
3588 for (auto &&Pair : Privates) {
3589 auto *VD = Pair.second.PrivateCopy;
3590 auto *Init = VD->getAnyInitializer();
3591 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3592 !CGF.isTrivialInitializer(Init));
3593 }
3594 return InitRequired;
3595}
3596
3597
3598/// Emit task_dup function (for initialization of
3599/// private/firstprivate/lastprivate vars and last_iter flag)
3600/// \code
3601/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3602/// lastpriv) {
3603/// // setup lastprivate flag
3604/// task_dst->last = lastpriv;
3605/// // could be constructor calls here...
3606/// }
3607/// \endcode
3608static llvm::Value *
3609emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3610 const OMPExecutableDirective &D,
3611 QualType KmpTaskTWithPrivatesPtrQTy,
3612 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3613 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3614 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3615 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3616 auto &C = CGM.getContext();
3617 FunctionArgList Args;
3618 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc,
3619 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3620 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc,
3621 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3622 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc,
3623 /*Id=*/nullptr, C.IntTy);
3624 Args.push_back(&DstArg);
3625 Args.push_back(&SrcArg);
3626 Args.push_back(&LastprivArg);
3627 auto &TaskDupFnInfo =
3628 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3629 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3630 auto *TaskDup =
3631 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3632 ".omp_task_dup.", &CGM.getModule());
3633 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3634 CodeGenFunction CGF(CGM);
3635 CGF.disableDebugInfo();
3636 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3637
3638 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3639 CGF.GetAddrOfLocalVar(&DstArg),
3640 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3641 // task_dst->liter = lastpriv;
3642 if (WithLastIter) {
3643 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3644 LValue Base = CGF.EmitLValueForField(
3645 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3646 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3647 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3648 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3649 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3650 }
3651
3652 // Emit initial values for private copies (if any).
3653 assert(!Privates.empty());
3654 Address KmpTaskSharedsPtr = Address::invalid();
3655 if (!Data.FirstprivateVars.empty()) {
3656 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3657 CGF.GetAddrOfLocalVar(&SrcArg),
3658 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3659 LValue Base = CGF.EmitLValueForField(
3660 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3661 KmpTaskSharedsPtr = Address(
3662 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3663 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3664 KmpTaskTShareds)),
3665 Loc),
3666 CGF.getNaturalTypeAlignment(SharedsTy));
3667 }
Alexey Bataev8a831592016-05-10 10:36:51 +00003668 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3669 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003670 CGF.FinishFunction();
3671 return TaskDup;
3672}
3673
Alexey Bataev8a831592016-05-10 10:36:51 +00003674/// Checks if destructor function is required to be generated.
3675/// \return true if cleanups are required, false otherwise.
3676static bool
3677checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3678 bool NeedsCleanup = false;
3679 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3680 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3681 for (auto *FD : PrivateRD->fields()) {
3682 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3683 if (NeedsCleanup)
3684 break;
3685 }
3686 return NeedsCleanup;
3687}
3688
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003689CGOpenMPRuntime::TaskResultTy
3690CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3691 const OMPExecutableDirective &D,
3692 llvm::Value *TaskFunction, QualType SharedsTy,
3693 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003694 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003695 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003696 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003697 auto I = Data.PrivateCopies.begin();
3698 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003699 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3700 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003701 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003702 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3703 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003704 ++I;
3705 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003706 I = Data.FirstprivateCopies.begin();
3707 auto IElemInitRef = Data.FirstprivateInits.begin();
3708 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003709 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3710 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003711 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003712 PrivateHelpersTy(
3713 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3714 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003715 ++I;
3716 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003717 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003718 I = Data.LastprivateCopies.begin();
3719 for (auto *E : Data.LastprivateVars) {
3720 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3721 Privates.push_back(std::make_pair(
3722 C.getDeclAlign(VD),
3723 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3724 /*PrivateElemInit=*/nullptr)));
3725 ++I;
3726 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003727 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3728 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003729 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3730 // Build type kmp_routine_entry_t (if not built yet).
3731 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003732 // Build type kmp_task_t (if not built yet).
3733 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003734 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3735 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003736 }
3737 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003738 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003739 auto *KmpTaskTWithPrivatesQTyRD =
3740 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3741 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3742 QualType KmpTaskTWithPrivatesPtrQTy =
3743 C.getPointerType(KmpTaskTWithPrivatesQTy);
3744 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3745 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003746 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003747 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3748
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003749 // Emit initial values for private copies (if any).
3750 llvm::Value *TaskPrivatesMap = nullptr;
3751 auto *TaskPrivatesMapTy =
3752 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3753 3)
3754 ->getType();
3755 if (!Privates.empty()) {
3756 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003757 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3758 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3759 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003760 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3761 TaskPrivatesMap, TaskPrivatesMapTy);
3762 } else {
3763 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3764 cast<llvm::PointerType>(TaskPrivatesMapTy));
3765 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003766 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3767 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003768 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003769 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3770 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3771 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003772
3773 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3774 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3775 // kmp_routine_entry_t *task_entry);
3776 // Task flags. Format is taken from
3777 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3778 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003779 enum {
3780 TiedFlag = 0x1,
3781 FinalFlag = 0x2,
3782 DestructorsFlag = 0x8,
3783 PriorityFlag = 0x20
3784 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003785 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00003786 bool NeedsCleanup = false;
3787 if (!Privates.empty()) {
3788 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3789 if (NeedsCleanup)
3790 Flags = Flags | DestructorsFlag;
3791 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003792 if (Data.Priority.getInt())
3793 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003794 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003795 Data.Final.getPointer()
3796 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00003797 CGF.Builder.getInt32(FinalFlag),
3798 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003799 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003800 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003801 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003802 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3803 getThreadID(CGF, Loc), TaskFlags,
3804 KmpTaskTWithPrivatesTySize, SharedsSize,
3805 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3806 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003807 auto *NewTask = CGF.EmitRuntimeCall(
3808 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003809 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3810 NewTask, KmpTaskTWithPrivatesPtrTy);
3811 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3812 KmpTaskTWithPrivatesQTy);
3813 LValue TDBase =
3814 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003815 // Fill the data in the resulting kmp_task_t record.
3816 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003817 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003818 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003819 KmpTaskSharedsPtr =
3820 Address(CGF.EmitLoadOfScalar(
3821 CGF.EmitLValueForField(
3822 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3823 KmpTaskTShareds)),
3824 Loc),
3825 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003826 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003827 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003828 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00003829 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003830 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003831 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3832 SharedsTy, SharedsPtrTy, Data, Privates,
3833 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003834 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3835 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3836 Result.TaskDupFn = emitTaskDupFunction(
3837 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3838 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3839 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003840 }
3841 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00003842 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3843 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00003844 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00003845 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3846 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3847 if (NeedsCleanup) {
3848 llvm::Value *DestructorFn = emitDestructorsFunction(
3849 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3850 KmpTaskTWithPrivatesQTy);
3851 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3852 LValue DestructorsLV = CGF.EmitLValueForField(
3853 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3854 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3855 DestructorFn, KmpRoutineEntryPtrTy),
3856 DestructorsLV);
3857 }
3858 // Set priority.
3859 if (Data.Priority.getInt()) {
3860 LValue Data2LV = CGF.EmitLValueForField(
3861 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3862 LValue PriorityLV = CGF.EmitLValueForField(
3863 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3864 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3865 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003866 Result.NewTask = NewTask;
3867 Result.TaskEntry = TaskEntry;
3868 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3869 Result.TDBase = TDBase;
3870 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3871 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00003872}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003873
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003874void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3875 const OMPExecutableDirective &D,
3876 llvm::Value *TaskFunction,
3877 QualType SharedsTy, Address Shareds,
3878 const Expr *IfCond,
3879 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003880 if (!CGF.HaveInsertPoint())
3881 return;
3882
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003883 TaskResultTy Result =
3884 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3885 llvm::Value *NewTask = Result.NewTask;
3886 llvm::Value *TaskEntry = Result.TaskEntry;
3887 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3888 LValue TDBase = Result.TDBase;
3889 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00003890 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003891 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003892 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003893 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00003894 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003895 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003896 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003897 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3898 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003899 QualType FlagsTy =
3900 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003901 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3902 if (KmpDependInfoTy.isNull()) {
3903 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3904 KmpDependInfoRD->startDefinition();
3905 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3906 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3907 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3908 KmpDependInfoRD->completeDefinition();
3909 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003910 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003911 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003912 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003913 // Define type kmp_depend_info[<Dependences.size()>];
3914 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003915 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003916 ArrayType::Normal, /*IndexTypeQuals=*/0);
3917 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003918 DependenciesArray =
3919 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003920 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003921 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00003922 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003923 llvm::Value *Size;
3924 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003925 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3926 LValue UpAddrLVal =
3927 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3928 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003929 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003930 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003931 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003932 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3933 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003934 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003935 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003936 auto Base = CGF.MakeAddrLValue(
3937 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003938 KmpDependInfoTy);
3939 // deps[i].base_addr = &<Dependences[i].second>;
3940 auto BaseAddrLVal = CGF.EmitLValueForField(
3941 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003942 CGF.EmitStoreOfScalar(
3943 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3944 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003945 // deps[i].len = sizeof(<Dependences[i].second>);
3946 auto LenLVal = CGF.EmitLValueForField(
3947 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3948 CGF.EmitStoreOfScalar(Size, LenLVal);
3949 // deps[i].flags = <Dependences[i].first>;
3950 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003951 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003952 case OMPC_DEPEND_in:
3953 DepKind = DepIn;
3954 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003955 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003956 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003957 case OMPC_DEPEND_inout:
3958 DepKind = DepInOut;
3959 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003960 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003961 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003962 case OMPC_DEPEND_unknown:
3963 llvm_unreachable("Unknown task dependence type");
3964 }
3965 auto FlagsLVal = CGF.EmitLValueForField(
3966 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3967 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3968 FlagsLVal);
3969 }
John McCall7f416cc2015-09-08 08:05:57 +00003970 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3971 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003972 CGF.VoidPtrTy);
3973 }
3974
Alexey Bataev62b63b12015-03-10 07:28:44 +00003975 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3976 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003977 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3978 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3979 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3980 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003981 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003982 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003983 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3984 llvm::Value *DepTaskArgs[7];
3985 if (NumDependencies) {
3986 DepTaskArgs[0] = UpLoc;
3987 DepTaskArgs[1] = ThreadID;
3988 DepTaskArgs[2] = NewTask;
3989 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3990 DepTaskArgs[4] = DependenciesArray.getPointer();
3991 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3992 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3993 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003994 auto &&ThenCodeGen = [this, Loc, &Data, TDBase, KmpTaskTQTyRD,
Alexey Bataev48591dd2016-04-20 04:01:36 +00003995 NumDependencies, &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003996 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003997 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003998 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3999 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4000 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4001 }
John McCall7f416cc2015-09-08 08:05:57 +00004002 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004003 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004004 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004005 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004006 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004007 TaskArgs);
4008 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004009 // Check if parent region is untied and build return for untied task;
4010 if (auto *Region =
4011 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4012 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004013 };
John McCall7f416cc2015-09-08 08:05:57 +00004014
4015 llvm::Value *DepWaitTaskArgs[6];
4016 if (NumDependencies) {
4017 DepWaitTaskArgs[0] = UpLoc;
4018 DepWaitTaskArgs[1] = ThreadID;
4019 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4020 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4021 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4022 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4023 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004024 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4025 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4026 PrePostActionTy &) {
4027 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004028 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4029 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4030 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4031 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4032 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004033 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004034 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004035 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004036 // Call proxy_task_entry(gtid, new_task);
4037 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4038 CodeGenFunction &CGF, PrePostActionTy &Action) {
4039 Action.Enter(CGF);
4040 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4041 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4042 };
4043
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004044 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4045 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004046 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4047 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004048 RegionCodeGenTy RCG(CodeGen);
4049 CommonActionTy Action(
4050 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4051 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4052 RCG.setAction(Action);
4053 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004054 };
John McCall7f416cc2015-09-08 08:05:57 +00004055
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004056 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004057 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004058 else {
4059 RegionCodeGenTy ThenRCG(ThenCodeGen);
4060 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004061 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004062}
4063
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004064void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4065 const OMPLoopDirective &D,
4066 llvm::Value *TaskFunction,
4067 QualType SharedsTy, Address Shareds,
4068 const Expr *IfCond,
4069 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004070 if (!CGF.HaveInsertPoint())
4071 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004072 TaskResultTy Result =
4073 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004074 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4075 // libcall.
4076 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4077 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4078 // sched, kmp_uint64 grainsize, void *task_dup);
4079 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4080 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4081 llvm::Value *IfVal;
4082 if (IfCond) {
4083 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4084 /*isSigned=*/true);
4085 } else
4086 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4087
4088 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004089 Result.TDBase,
4090 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004091 auto *LBVar =
4092 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4093 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4094 /*IsInitializer=*/true);
4095 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004096 Result.TDBase,
4097 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004098 auto *UBVar =
4099 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4100 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4101 /*IsInitializer=*/true);
4102 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004103 Result.TDBase,
4104 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004105 auto *StVar =
4106 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4107 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4108 /*IsInitializer=*/true);
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004109 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004110 llvm::Value *TaskArgs[] = {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004111 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004112 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004113 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004114 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004115 CGF.IntTy, Data.Schedule.getPointer()
4116 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004117 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004118 Data.Schedule.getPointer()
4119 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004120 /*isSigned=*/false)
4121 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataevf93095a2016-05-05 08:46:22 +00004122 Result.TaskDupFn
4123 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4124 CGF.VoidPtrTy)
4125 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004126 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4127}
4128
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004129/// \brief Emit reduction operation for each element of array (required for
4130/// array sections) LHS op = RHS.
4131/// \param Type Type of array.
4132/// \param LHSVar Variable on the left side of the reduction operation
4133/// (references element of array in original variable).
4134/// \param RHSVar Variable on the right side of the reduction operation
4135/// (references element of array in original variable).
4136/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4137/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004138static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004139 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4140 const VarDecl *RHSVar,
4141 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4142 const Expr *, const Expr *)> &RedOpGen,
4143 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4144 const Expr *UpExpr = nullptr) {
4145 // Perform element-by-element initialization.
4146 QualType ElementTy;
4147 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4148 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4149
4150 // Drill down to the base element type on both arrays.
4151 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4152 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4153
4154 auto RHSBegin = RHSAddr.getPointer();
4155 auto LHSBegin = LHSAddr.getPointer();
4156 // Cast from pointer to array type to pointer to single element.
4157 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4158 // The basic structure here is a while-do loop.
4159 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4160 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4161 auto IsEmpty =
4162 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4163 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4164
4165 // Enter the loop body, making that address the current address.
4166 auto EntryBB = CGF.Builder.GetInsertBlock();
4167 CGF.EmitBlock(BodyBB);
4168
4169 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4170
4171 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4172 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4173 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4174 Address RHSElementCurrent =
4175 Address(RHSElementPHI,
4176 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4177
4178 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4179 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4180 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4181 Address LHSElementCurrent =
4182 Address(LHSElementPHI,
4183 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4184
4185 // Emit copy.
4186 CodeGenFunction::OMPPrivateScope Scope(CGF);
4187 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4188 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4189 Scope.Privatize();
4190 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4191 Scope.ForceCleanup();
4192
4193 // Shift the address forward by one element.
4194 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4195 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4196 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4197 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4198 // Check whether we've reached the end.
4199 auto Done =
4200 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4201 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4202 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4203 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4204
4205 // Done.
4206 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4207}
4208
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004209/// Emit reduction combiner. If the combiner is a simple expression emit it as
4210/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4211/// UDR combiner function.
4212static void emitReductionCombiner(CodeGenFunction &CGF,
4213 const Expr *ReductionOp) {
4214 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4215 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4216 if (auto *DRE =
4217 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4218 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4219 std::pair<llvm::Function *, llvm::Function *> Reduction =
4220 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4221 RValue Func = RValue::get(Reduction.first);
4222 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4223 CGF.EmitIgnoredExpr(ReductionOp);
4224 return;
4225 }
4226 CGF.EmitIgnoredExpr(ReductionOp);
4227}
4228
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004229static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
4230 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004231 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004232 ArrayRef<const Expr *> LHSExprs,
4233 ArrayRef<const Expr *> RHSExprs,
4234 ArrayRef<const Expr *> ReductionOps) {
4235 auto &C = CGM.getContext();
4236
4237 // void reduction_func(void *LHSArg, void *RHSArg);
4238 FunctionArgList Args;
4239 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4240 C.VoidPtrTy);
4241 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4242 C.VoidPtrTy);
4243 Args.push_back(&LHSArg);
4244 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004245 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004246 auto *Fn = llvm::Function::Create(
4247 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4248 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004249 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004250 CodeGenFunction CGF(CGM);
4251 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4252
4253 // Dst = (void*[n])(LHSArg);
4254 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004255 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4256 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4257 ArgsType), CGF.getPointerAlign());
4258 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4259 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4260 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004261
4262 // ...
4263 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4264 // ...
4265 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004266 auto IPriv = Privates.begin();
4267 unsigned Idx = 0;
4268 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004269 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4270 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004271 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004272 });
4273 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4274 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004275 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004276 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004277 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004278 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004279 // Get array size and emit VLA type.
4280 ++Idx;
4281 Address Elem =
4282 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4283 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004284 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4285 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004286 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004287 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004288 CGF.EmitVariablyModifiedType(PrivTy);
4289 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004290 }
4291 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004292 IPriv = Privates.begin();
4293 auto ILHS = LHSExprs.begin();
4294 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004295 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004296 if ((*IPriv)->getType()->isArrayType()) {
4297 // Emit reduction for array section.
4298 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4299 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004300 EmitOMPAggregateReduction(
4301 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4302 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4303 emitReductionCombiner(CGF, E);
4304 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004305 } else
4306 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004307 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004308 ++IPriv;
4309 ++ILHS;
4310 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004311 }
4312 Scope.ForceCleanup();
4313 CGF.FinishFunction();
4314 return Fn;
4315}
4316
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004317static void emitSingleReductionCombiner(CodeGenFunction &CGF,
4318 const Expr *ReductionOp,
4319 const Expr *PrivateRef,
4320 const DeclRefExpr *LHS,
4321 const DeclRefExpr *RHS) {
4322 if (PrivateRef->getType()->isArrayType()) {
4323 // Emit reduction for array section.
4324 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4325 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4326 EmitOMPAggregateReduction(
4327 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4328 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4329 emitReductionCombiner(CGF, ReductionOp);
4330 });
4331 } else
4332 // Emit reduction for array subscript or single variable.
4333 emitReductionCombiner(CGF, ReductionOp);
4334}
4335
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004336void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004337 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004338 ArrayRef<const Expr *> LHSExprs,
4339 ArrayRef<const Expr *> RHSExprs,
4340 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004341 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004342 if (!CGF.HaveInsertPoint())
4343 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004344 // Next code should be emitted for reduction:
4345 //
4346 // static kmp_critical_name lock = { 0 };
4347 //
4348 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4349 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4350 // ...
4351 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4352 // *(Type<n>-1*)rhs[<n>-1]);
4353 // }
4354 //
4355 // ...
4356 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4357 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4358 // RedList, reduce_func, &<lock>)) {
4359 // case 1:
4360 // ...
4361 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4362 // ...
4363 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4364 // break;
4365 // case 2:
4366 // ...
4367 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4368 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004369 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004370 // break;
4371 // default:;
4372 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004373 //
4374 // if SimpleReduction is true, only the next code is generated:
4375 // ...
4376 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4377 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004378
4379 auto &C = CGM.getContext();
4380
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004381 if (SimpleReduction) {
4382 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004383 auto IPriv = Privates.begin();
4384 auto ILHS = LHSExprs.begin();
4385 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004386 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004387 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4388 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004389 ++IPriv;
4390 ++ILHS;
4391 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004392 }
4393 return;
4394 }
4395
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004396 // 1. Build a list of reduction variables.
4397 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004398 auto Size = RHSExprs.size();
4399 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004400 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004401 // Reserve place for array size.
4402 ++Size;
4403 }
4404 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004405 QualType ReductionArrayTy =
4406 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4407 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004408 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004409 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004410 auto IPriv = Privates.begin();
4411 unsigned Idx = 0;
4412 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004413 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004414 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004415 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004416 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004417 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4418 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004419 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004420 // Store array size.
4421 ++Idx;
4422 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4423 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004424 llvm::Value *Size = CGF.Builder.CreateIntCast(
4425 CGF.getVLASize(
4426 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4427 .first,
4428 CGF.SizeTy, /*isSigned=*/false);
4429 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4430 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004431 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004432 }
4433
4434 // 2. Emit reduce_func().
4435 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004436 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4437 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004438
4439 // 3. Create static kmp_critical_name lock = { 0 };
4440 auto *Lock = getCriticalRegionLock(".reduction");
4441
4442 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4443 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004444 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004445 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004446 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004447 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4448 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004449 llvm::Value *Args[] = {
4450 IdentTLoc, // ident_t *<loc>
4451 ThreadId, // i32 <gtid>
4452 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4453 ReductionArrayTySize, // size_type sizeof(RedList)
4454 RL, // void *RedList
4455 ReductionFn, // void (*) (void *, void *) <reduce_func>
4456 Lock // kmp_critical_name *&<lock>
4457 };
4458 auto Res = CGF.EmitRuntimeCall(
4459 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4460 : OMPRTL__kmpc_reduce),
4461 Args);
4462
4463 // 5. Build switch(res)
4464 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4465 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4466
4467 // 6. Build case 1:
4468 // ...
4469 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4470 // ...
4471 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4472 // break;
4473 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4474 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4475 CGF.EmitBlock(Case1BB);
4476
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004477 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4478 llvm::Value *EndArgs[] = {
4479 IdentTLoc, // ident_t *<loc>
4480 ThreadId, // i32 <gtid>
4481 Lock // kmp_critical_name *&<lock>
4482 };
4483 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4484 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004485 auto IPriv = Privates.begin();
4486 auto ILHS = LHSExprs.begin();
4487 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004488 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004489 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4490 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004491 ++IPriv;
4492 ++ILHS;
4493 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004494 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004495 };
4496 RegionCodeGenTy RCG(CodeGen);
4497 CommonActionTy Action(
4498 nullptr, llvm::None,
4499 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4500 : OMPRTL__kmpc_end_reduce),
4501 EndArgs);
4502 RCG.setAction(Action);
4503 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004504
4505 CGF.EmitBranch(DefaultBB);
4506
4507 // 7. Build case 2:
4508 // ...
4509 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4510 // ...
4511 // break;
4512 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4513 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4514 CGF.EmitBlock(Case2BB);
4515
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004516 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4517 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004518 auto ILHS = LHSExprs.begin();
4519 auto IRHS = RHSExprs.begin();
4520 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004521 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004522 const Expr *XExpr = nullptr;
4523 const Expr *EExpr = nullptr;
4524 const Expr *UpExpr = nullptr;
4525 BinaryOperatorKind BO = BO_Comma;
4526 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4527 if (BO->getOpcode() == BO_Assign) {
4528 XExpr = BO->getLHS();
4529 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004530 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004531 }
4532 // Try to emit update expression as a simple atomic.
4533 auto *RHSExpr = UpExpr;
4534 if (RHSExpr) {
4535 // Analyze RHS part of the whole expression.
4536 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4537 RHSExpr->IgnoreParenImpCasts())) {
4538 // If this is a conditional operator, analyze its condition for
4539 // min/max reduction operator.
4540 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004541 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004542 if (auto *BORHS =
4543 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4544 EExpr = BORHS->getRHS();
4545 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004546 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004547 }
4548 if (XExpr) {
4549 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4550 auto &&AtomicRedGen = [BO, VD, IPriv,
4551 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4552 const Expr *EExpr, const Expr *UpExpr) {
4553 LValue X = CGF.EmitLValue(XExpr);
4554 RValue E;
4555 if (EExpr)
4556 E = CGF.EmitAnyExpr(EExpr);
4557 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004558 X, E, BO, /*IsXLHSInRHSPart=*/true,
4559 llvm::AtomicOrdering::Monotonic, Loc,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004560 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
4561 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4562 PrivateScope.addPrivate(
4563 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4564 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4565 CGF.emitOMPSimpleStore(
4566 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4567 VD->getType().getNonReferenceType(), Loc);
4568 return LHSTemp;
4569 });
4570 (void)PrivateScope.Privatize();
4571 return CGF.EmitAnyExpr(UpExpr);
4572 });
4573 };
4574 if ((*IPriv)->getType()->isArrayType()) {
4575 // Emit atomic reduction for array section.
4576 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4577 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4578 AtomicRedGen, XExpr, EExpr, UpExpr);
4579 } else
4580 // Emit atomic reduction for array subscript or single variable.
4581 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4582 } else {
4583 // Emit as a critical region.
4584 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4585 const Expr *, const Expr *) {
4586 auto &RT = CGF.CGM.getOpenMPRuntime();
4587 RT.emitCriticalRegion(
4588 CGF, ".atomic_reduction",
4589 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4590 Action.Enter(CGF);
4591 emitReductionCombiner(CGF, E);
4592 },
4593 Loc);
4594 };
4595 if ((*IPriv)->getType()->isArrayType()) {
4596 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4597 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4598 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4599 CritRedGen);
4600 } else
4601 CritRedGen(CGF, nullptr, nullptr, nullptr);
4602 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004603 ++ILHS;
4604 ++IRHS;
4605 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004606 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004607 };
4608 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4609 if (!WithNowait) {
4610 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4611 llvm::Value *EndArgs[] = {
4612 IdentTLoc, // ident_t *<loc>
4613 ThreadId, // i32 <gtid>
4614 Lock // kmp_critical_name *&<lock>
4615 };
4616 CommonActionTy Action(nullptr, llvm::None,
4617 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4618 EndArgs);
4619 AtomicRCG.setAction(Action);
4620 AtomicRCG(CGF);
4621 } else
4622 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004623
4624 CGF.EmitBranch(DefaultBB);
4625 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4626}
4627
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004628void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4629 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004630 if (!CGF.HaveInsertPoint())
4631 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004632 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4633 // global_tid);
4634 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4635 // Ignore return result until untied tasks are supported.
4636 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004637 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4638 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004639}
4640
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004641void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004642 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004643 const RegionCodeGenTy &CodeGen,
4644 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004645 if (!CGF.HaveInsertPoint())
4646 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004647 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004648 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004649}
4650
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004651namespace {
4652enum RTCancelKind {
4653 CancelNoreq = 0,
4654 CancelParallel = 1,
4655 CancelLoop = 2,
4656 CancelSections = 3,
4657 CancelTaskgroup = 4
4658};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004659} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004660
4661static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4662 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004663 if (CancelRegion == OMPD_parallel)
4664 CancelKind = CancelParallel;
4665 else if (CancelRegion == OMPD_for)
4666 CancelKind = CancelLoop;
4667 else if (CancelRegion == OMPD_sections)
4668 CancelKind = CancelSections;
4669 else {
4670 assert(CancelRegion == OMPD_taskgroup);
4671 CancelKind = CancelTaskgroup;
4672 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004673 return CancelKind;
4674}
4675
4676void CGOpenMPRuntime::emitCancellationPointCall(
4677 CodeGenFunction &CGF, SourceLocation Loc,
4678 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004679 if (!CGF.HaveInsertPoint())
4680 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004681 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4682 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004683 if (auto *OMPRegionInfo =
4684 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004685 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004686 llvm::Value *Args[] = {
4687 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4688 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004689 // Ignore return result until untied tasks are supported.
4690 auto *Result = CGF.EmitRuntimeCall(
4691 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4692 // if (__kmpc_cancellationpoint()) {
4693 // __kmpc_cancel_barrier();
4694 // exit from construct;
4695 // }
4696 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4697 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4698 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4699 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4700 CGF.EmitBlock(ExitBB);
4701 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004702 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004703 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004704 auto CancelDest =
4705 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004706 CGF.EmitBranchThroughCleanup(CancelDest);
4707 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4708 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004709 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004710}
4711
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004712void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004713 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004714 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004715 if (!CGF.HaveInsertPoint())
4716 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004717 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4718 // kmp_int32 cncl_kind);
4719 if (auto *OMPRegionInfo =
4720 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004721 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4722 PrePostActionTy &) {
4723 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004724 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004725 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004726 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4727 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004728 auto *Result = CGF.EmitRuntimeCall(
4729 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004730 // if (__kmpc_cancel()) {
4731 // __kmpc_cancel_barrier();
4732 // exit from construct;
4733 // }
4734 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4735 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4736 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4737 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4738 CGF.EmitBlock(ExitBB);
4739 // __kmpc_cancel_barrier();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004740 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev87933c72015-09-18 08:07:34 +00004741 // exit from construct;
4742 auto CancelDest =
4743 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4744 CGF.EmitBranchThroughCleanup(CancelDest);
4745 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4746 };
4747 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004748 emitOMPIfClause(CGF, IfCond, ThenGen,
4749 [](CodeGenFunction &, PrePostActionTy &) {});
4750 else {
4751 RegionCodeGenTy ThenRCG(ThenGen);
4752 ThenRCG(CGF);
4753 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004754 }
4755}
Samuel Antaobed3c462015-10-02 16:14:20 +00004756
Samuel Antaoee8fb302016-01-06 13:42:12 +00004757/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004758/// consists of the file and device IDs as well as line number associated with
4759/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004760static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4761 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004762 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004763
4764 auto &SM = C.getSourceManager();
4765
4766 // The loc should be always valid and have a file ID (the user cannot use
4767 // #pragma directives in macros)
4768
4769 assert(Loc.isValid() && "Source location is expected to be always valid.");
4770 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4771
4772 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4773 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4774
4775 llvm::sys::fs::UniqueID ID;
4776 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4777 llvm_unreachable("Source file with target region no longer exists!");
4778
4779 DeviceID = ID.getDevice();
4780 FileID = ID.getFile();
4781 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004782}
4783
4784void CGOpenMPRuntime::emitTargetOutlinedFunction(
4785 const OMPExecutableDirective &D, StringRef ParentName,
4786 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004787 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004788 assert(!ParentName.empty() && "Invalid target region parent name!");
4789
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004790 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4791 IsOffloadEntry, CodeGen);
4792}
4793
4794void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4795 const OMPExecutableDirective &D, StringRef ParentName,
4796 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4797 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004798 // Create a unique name for the entry function using the source location
4799 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004800 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004801 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004802 //
4803 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004804 // mangled name of the function that encloses the target region and BB is the
4805 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004806
4807 unsigned DeviceID;
4808 unsigned FileID;
4809 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004810 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004811 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004812 SmallString<64> EntryFnName;
4813 {
4814 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004815 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4816 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004817 }
4818
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004819 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4820
Samuel Antaobed3c462015-10-02 16:14:20 +00004821 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004822 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004823 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004824
Samuel Antao6d004262016-06-16 18:39:34 +00004825 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004826
4827 // If this target outline function is not an offload entry, we don't need to
4828 // register it.
4829 if (!IsOffloadEntry)
4830 return;
4831
4832 // The target region ID is used by the runtime library to identify the current
4833 // target region, so it only has to be unique and not necessarily point to
4834 // anything. It could be the pointer to the outlined function that implements
4835 // the target region, but we aren't using that so that the compiler doesn't
4836 // need to keep that, and could therefore inline the host function if proven
4837 // worthwhile during optimization. In the other hand, if emitting code for the
4838 // device, the ID has to be the function address so that it can retrieved from
4839 // the offloading entry and launched by the runtime library. We also mark the
4840 // outlined function to have external linkage in case we are emitting code for
4841 // the device, because these functions will be entry points to the device.
4842
4843 if (CGM.getLangOpts().OpenMPIsDevice) {
4844 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4845 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4846 } else
4847 OutlinedFnID = new llvm::GlobalVariable(
4848 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4849 llvm::GlobalValue::PrivateLinkage,
4850 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4851
4852 // Register the information for the entry associated with this target region.
4853 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004854 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004855}
4856
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004857/// discard all CompoundStmts intervening between two constructs
4858static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4859 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4860 Body = CS->body_front();
4861
4862 return Body;
4863}
4864
Samuel Antaob68e2db2016-03-03 16:20:23 +00004865/// \brief Emit the num_teams clause of an enclosed teams directive at the
4866/// target region scope. If there is no teams directive associated with the
4867/// target directive, or if there is no num_teams clause associated with the
4868/// enclosed teams directive, return nullptr.
4869static llvm::Value *
4870emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4871 CodeGenFunction &CGF,
4872 const OMPExecutableDirective &D) {
4873
4874 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4875 "teams directive expected to be "
4876 "emitted only for the host!");
4877
4878 // FIXME: For the moment we do not support combined directives with target and
4879 // teams, so we do not expect to get any num_teams clause in the provided
4880 // directive. Once we support that, this assertion can be replaced by the
4881 // actual emission of the clause expression.
4882 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4883 "Not expecting clause in directive.");
4884
4885 // If the current target region has a teams region enclosed, we need to get
4886 // the number of teams to pass to the runtime function call. This is done
4887 // by generating the expression in a inlined region. This is required because
4888 // the expression is captured in the enclosing target environment when the
4889 // teams directive is not combined with target.
4890
4891 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4892
4893 // FIXME: Accommodate other combined directives with teams when they become
4894 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004895 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4896 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004897 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4898 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4899 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4900 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4901 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4902 /*IsSigned=*/true);
4903 }
4904
4905 // If we have an enclosed teams directive but no num_teams clause we use
4906 // the default value 0.
4907 return CGF.Builder.getInt32(0);
4908 }
4909
4910 // No teams associated with the directive.
4911 return nullptr;
4912}
4913
4914/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4915/// target region scope. If there is no teams directive associated with the
4916/// target directive, or if there is no thread_limit clause associated with the
4917/// enclosed teams directive, return nullptr.
4918static llvm::Value *
4919emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4920 CodeGenFunction &CGF,
4921 const OMPExecutableDirective &D) {
4922
4923 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4924 "teams directive expected to be "
4925 "emitted only for the host!");
4926
4927 // FIXME: For the moment we do not support combined directives with target and
4928 // teams, so we do not expect to get any thread_limit clause in the provided
4929 // directive. Once we support that, this assertion can be replaced by the
4930 // actual emission of the clause expression.
4931 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4932 "Not expecting clause in directive.");
4933
4934 // If the current target region has a teams region enclosed, we need to get
4935 // the thread limit to pass to the runtime function call. This is done
4936 // by generating the expression in a inlined region. This is required because
4937 // the expression is captured in the enclosing target environment when the
4938 // teams directive is not combined with target.
4939
4940 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4941
4942 // FIXME: Accommodate other combined directives with teams when they become
4943 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004944 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4945 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004946 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4947 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4948 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4949 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4950 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4951 /*IsSigned=*/true);
4952 }
4953
4954 // If we have an enclosed teams directive but no thread_limit clause we use
4955 // the default value 0.
4956 return CGF.Builder.getInt32(0);
4957 }
4958
4959 // No teams associated with the directive.
4960 return nullptr;
4961}
4962
Samuel Antao86ace552016-04-27 22:40:57 +00004963namespace {
4964// \brief Utility to handle information from clauses associated with a given
4965// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
4966// It provides a convenient interface to obtain the information and generate
4967// code for that information.
4968class MappableExprsHandler {
4969public:
4970 /// \brief Values for bit flags used to specify the mapping type for
4971 /// offloading.
4972 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00004973 /// \brief Allocate memory on the device and move data from host to device.
4974 OMP_MAP_TO = 0x01,
4975 /// \brief Allocate memory on the device and move data from device to host.
4976 OMP_MAP_FROM = 0x02,
4977 /// \brief Always perform the requested mapping action on the element, even
4978 /// if it was already mapped before.
4979 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00004980 /// \brief Delete the element from the device environment, ignoring the
4981 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00004982 OMP_MAP_DELETE = 0x08,
4983 /// \brief The element being mapped is a pointer, therefore the pointee
4984 /// should be mapped as well.
4985 OMP_MAP_IS_PTR = 0x10,
4986 /// \brief This flags signals that an argument is the first one relating to
4987 /// a map/private clause expression. For some cases a single
4988 /// map/privatization results in multiple arguments passed to the runtime
4989 /// library.
4990 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00004991 /// \brief Signal that the runtime library has to return the device pointer
4992 /// in the current position for the data being mapped.
4993 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00004994 /// \brief This flag signals that the reference being passed is a pointer to
4995 /// private data.
4996 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00004997 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00004998 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00004999 };
5000
Samuel Antaocc10b852016-07-28 14:23:26 +00005001 /// Class that associates information with a base pointer to be passed to the
5002 /// runtime library.
5003 class BasePointerInfo {
5004 /// The base pointer.
5005 llvm::Value *Ptr = nullptr;
5006 /// The base declaration that refers to this device pointer, or null if
5007 /// there is none.
5008 const ValueDecl *DevPtrDecl = nullptr;
5009
5010 public:
5011 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5012 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5013 llvm::Value *operator*() const { return Ptr; }
5014 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5015 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5016 };
5017
5018 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005019 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5020 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5021
5022private:
5023 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005024 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005025
5026 /// \brief Function the directive is being generated for.
5027 CodeGenFunction &CGF;
5028
Samuel Antaod486f842016-05-26 16:53:38 +00005029 /// \brief Set of all first private variables in the current directive.
5030 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5031
Samuel Antao6890b092016-07-28 14:25:09 +00005032 /// Map between device pointer declarations and their expression components.
5033 /// The key value for declarations in 'this' is null.
5034 llvm::DenseMap<
5035 const ValueDecl *,
5036 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5037 DevPointersMap;
5038
Samuel Antao86ace552016-04-27 22:40:57 +00005039 llvm::Value *getExprTypeSize(const Expr *E) const {
5040 auto ExprTy = E->getType().getCanonicalType();
5041
5042 // Reference types are ignored for mapping purposes.
5043 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5044 ExprTy = RefTy->getPointeeType().getCanonicalType();
5045
5046 // Given that an array section is considered a built-in type, we need to
5047 // do the calculation based on the length of the section instead of relying
5048 // on CGF.getTypeSize(E->getType()).
5049 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5050 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5051 OAE->getBase()->IgnoreParenImpCasts())
5052 .getCanonicalType();
5053
5054 // If there is no length associated with the expression, that means we
5055 // are using the whole length of the base.
5056 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5057 return CGF.getTypeSize(BaseTy);
5058
5059 llvm::Value *ElemSize;
5060 if (auto *PTy = BaseTy->getAs<PointerType>())
5061 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5062 else {
5063 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5064 assert(ATy && "Expecting array type if not a pointer type.");
5065 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5066 }
5067
5068 // If we don't have a length at this point, that is because we have an
5069 // array section with a single element.
5070 if (!OAE->getLength())
5071 return ElemSize;
5072
5073 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5074 LengthVal =
5075 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5076 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5077 }
5078 return CGF.getTypeSize(ExprTy);
5079 }
5080
5081 /// \brief Return the corresponding bits for a given map clause modifier. Add
5082 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00005083 /// map as the first one of a series of maps that relate to the same map
5084 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00005085 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5086 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00005087 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00005088 unsigned Bits = 0u;
5089 switch (MapType) {
5090 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00005091 case OMPC_MAP_release:
5092 // alloc and release is the default behavior in the runtime library, i.e.
5093 // if we don't pass any bits alloc/release that is what the runtime is
5094 // going to do. Therefore, we don't need to signal anything for these two
5095 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00005096 break;
5097 case OMPC_MAP_to:
5098 Bits = OMP_MAP_TO;
5099 break;
5100 case OMPC_MAP_from:
5101 Bits = OMP_MAP_FROM;
5102 break;
5103 case OMPC_MAP_tofrom:
5104 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5105 break;
5106 case OMPC_MAP_delete:
5107 Bits = OMP_MAP_DELETE;
5108 break;
Samuel Antao86ace552016-04-27 22:40:57 +00005109 default:
5110 llvm_unreachable("Unexpected map type!");
5111 break;
5112 }
5113 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00005114 Bits |= OMP_MAP_IS_PTR;
5115 if (AddIsFirstFlag)
5116 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00005117 if (MapTypeModifier == OMPC_MAP_always)
5118 Bits |= OMP_MAP_ALWAYS;
5119 return Bits;
5120 }
5121
5122 /// \brief Return true if the provided expression is a final array section. A
5123 /// final array section, is one whose length can't be proved to be one.
5124 bool isFinalArraySectionExpression(const Expr *E) const {
5125 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5126
5127 // It is not an array section and therefore not a unity-size one.
5128 if (!OASE)
5129 return false;
5130
5131 // An array section with no colon always refer to a single element.
5132 if (OASE->getColonLoc().isInvalid())
5133 return false;
5134
5135 auto *Length = OASE->getLength();
5136
5137 // If we don't have a length we have to check if the array has size 1
5138 // for this dimension. Also, we should always expect a length if the
5139 // base type is pointer.
5140 if (!Length) {
5141 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5142 OASE->getBase()->IgnoreParenImpCasts())
5143 .getCanonicalType();
5144 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5145 return ATy->getSize().getSExtValue() != 1;
5146 // If we don't have a constant dimension length, we have to consider
5147 // the current section as having any size, so it is not necessarily
5148 // unitary. If it happen to be unity size, that's user fault.
5149 return true;
5150 }
5151
5152 // Check if the length evaluates to 1.
5153 llvm::APSInt ConstLength;
5154 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5155 return true; // Can have more that size 1.
5156
5157 return ConstLength.getSExtValue() != 1;
5158 }
5159
5160 /// \brief Generate the base pointers, section pointers, sizes and map type
5161 /// bits for the provided map type, map modifier, and expression components.
5162 /// \a IsFirstComponent should be set to true if the provided set of
5163 /// components is the first associated with a capture.
5164 void generateInfoForComponentList(
5165 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5166 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00005167 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005168 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5169 bool IsFirstComponentList) const {
5170
5171 // The following summarizes what has to be generated for each map and the
5172 // types bellow. The generated information is expressed in this order:
5173 // base pointer, section pointer, size, flags
5174 // (to add to the ones that come from the map type and modifier).
5175 //
5176 // double d;
5177 // int i[100];
5178 // float *p;
5179 //
5180 // struct S1 {
5181 // int i;
5182 // float f[50];
5183 // }
5184 // struct S2 {
5185 // int i;
5186 // float f[50];
5187 // S1 s;
5188 // double *p;
5189 // struct S2 *ps;
5190 // }
5191 // S2 s;
5192 // S2 *ps;
5193 //
5194 // map(d)
5195 // &d, &d, sizeof(double), noflags
5196 //
5197 // map(i)
5198 // &i, &i, 100*sizeof(int), noflags
5199 //
5200 // map(i[1:23])
5201 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5202 //
5203 // map(p)
5204 // &p, &p, sizeof(float*), noflags
5205 //
5206 // map(p[1:24])
5207 // p, &p[1], 24*sizeof(float), noflags
5208 //
5209 // map(s)
5210 // &s, &s, sizeof(S2), noflags
5211 //
5212 // map(s.i)
5213 // &s, &(s.i), sizeof(int), noflags
5214 //
5215 // map(s.s.f)
5216 // &s, &(s.i.f), 50*sizeof(int), noflags
5217 //
5218 // map(s.p)
5219 // &s, &(s.p), sizeof(double*), noflags
5220 //
5221 // map(s.p[:22], s.a s.b)
5222 // &s, &(s.p), sizeof(double*), noflags
5223 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5224 //
5225 // map(s.ps)
5226 // &s, &(s.ps), sizeof(S2*), noflags
5227 //
5228 // map(s.ps->s.i)
5229 // &s, &(s.ps), sizeof(S2*), noflags
5230 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5231 //
5232 // map(s.ps->ps)
5233 // &s, &(s.ps), sizeof(S2*), noflags
5234 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5235 //
5236 // map(s.ps->ps->ps)
5237 // &s, &(s.ps), sizeof(S2*), noflags
5238 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5239 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5240 //
5241 // map(s.ps->ps->s.f[:22])
5242 // &s, &(s.ps), sizeof(S2*), noflags
5243 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5244 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5245 //
5246 // map(ps)
5247 // &ps, &ps, sizeof(S2*), noflags
5248 //
5249 // map(ps->i)
5250 // ps, &(ps->i), sizeof(int), noflags
5251 //
5252 // map(ps->s.f)
5253 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5254 //
5255 // map(ps->p)
5256 // ps, &(ps->p), sizeof(double*), noflags
5257 //
5258 // map(ps->p[:22])
5259 // ps, &(ps->p), sizeof(double*), noflags
5260 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5261 //
5262 // map(ps->ps)
5263 // ps, &(ps->ps), sizeof(S2*), noflags
5264 //
5265 // map(ps->ps->s.i)
5266 // ps, &(ps->ps), sizeof(S2*), noflags
5267 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5268 //
5269 // map(ps->ps->ps)
5270 // ps, &(ps->ps), sizeof(S2*), noflags
5271 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5272 //
5273 // map(ps->ps->ps->ps)
5274 // ps, &(ps->ps), sizeof(S2*), noflags
5275 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5276 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5277 //
5278 // map(ps->ps->ps->s.f[:22])
5279 // ps, &(ps->ps), sizeof(S2*), noflags
5280 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5281 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5282 // extra_flag
5283
5284 // Track if the map information being generated is the first for a capture.
5285 bool IsCaptureFirstInfo = IsFirstComponentList;
5286
5287 // Scan the components from the base to the complete expression.
5288 auto CI = Components.rbegin();
5289 auto CE = Components.rend();
5290 auto I = CI;
5291
5292 // Track if the map information being generated is the first for a list of
5293 // components.
5294 bool IsExpressionFirstInfo = true;
5295 llvm::Value *BP = nullptr;
5296
5297 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5298 // The base is the 'this' pointer. The content of the pointer is going
5299 // to be the base of the field being mapped.
5300 BP = CGF.EmitScalarExpr(ME->getBase());
5301 } else {
5302 // The base is the reference to the variable.
5303 // BP = &Var.
5304 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5305 .getPointer();
5306
5307 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00005308 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00005309 // reference. References are ignored for mapping purposes.
5310 QualType Ty =
5311 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5312 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5313 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00005314 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00005315 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00005316 .getPointer();
5317
5318 // We do not need to generate individual map information for the
5319 // pointer, it can be associated with the combined storage.
5320 ++I;
5321 }
5322 }
5323
5324 for (; I != CE; ++I) {
5325 auto Next = std::next(I);
5326
5327 // We need to generate the addresses and sizes if this is the last
5328 // component, if the component is a pointer or if it is an array section
5329 // whose length can't be proved to be one. If this is a pointer, it
5330 // becomes the base address for the following components.
5331
5332 // A final array section, is one whose length can't be proved to be one.
5333 bool IsFinalArraySection =
5334 isFinalArraySectionExpression(I->getAssociatedExpression());
5335
5336 // Get information on whether the element is a pointer. Have to do a
5337 // special treatment for array sections given that they are built-in
5338 // types.
5339 const auto *OASE =
5340 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5341 bool IsPointer =
5342 (OASE &&
5343 OMPArraySectionExpr::getBaseOriginalType(OASE)
5344 .getCanonicalType()
5345 ->isAnyPointerType()) ||
5346 I->getAssociatedExpression()->getType()->isAnyPointerType();
5347
5348 if (Next == CE || IsPointer || IsFinalArraySection) {
5349
5350 // If this is not the last component, we expect the pointer to be
5351 // associated with an array expression or member expression.
5352 assert((Next == CE ||
5353 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5354 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5355 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5356 "Unexpected expression");
5357
Samuel Antao86ace552016-04-27 22:40:57 +00005358 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5359 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5360
Samuel Antao03a3cec2016-07-27 22:52:16 +00005361 // If we have a member expression and the current component is a
5362 // reference, we have to map the reference too. Whenever we have a
5363 // reference, the section that reference refers to is going to be a
5364 // load instruction from the storage assigned to the reference.
5365 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5366 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5367 auto *LI = cast<llvm::LoadInst>(LB);
5368 auto *RefAddr = LI->getPointerOperand();
5369
5370 BasePointers.push_back(BP);
5371 Pointers.push_back(RefAddr);
5372 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5373 Types.push_back(getMapTypeBits(
5374 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5375 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5376 IsExpressionFirstInfo = false;
5377 IsCaptureFirstInfo = false;
5378 // The reference will be the next base address.
5379 BP = RefAddr;
5380 }
5381
5382 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00005383 Pointers.push_back(LB);
5384 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00005385
Samuel Antao6782e942016-05-26 16:48:10 +00005386 // We need to add a pointer flag for each map that comes from the
5387 // same expression except for the first one. We also need to signal
5388 // this map is the first one that relates with the current capture
5389 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00005390 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5391 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00005392 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00005393
5394 // If we have a final array section, we are done with this expression.
5395 if (IsFinalArraySection)
5396 break;
5397
5398 // The pointer becomes the base for the next element.
5399 if (Next != CE)
5400 BP = LB;
5401
5402 IsExpressionFirstInfo = false;
5403 IsCaptureFirstInfo = false;
5404 continue;
5405 }
5406 }
5407 }
5408
Samuel Antaod486f842016-05-26 16:53:38 +00005409 /// \brief Return the adjusted map modifiers if the declaration a capture
5410 /// refers to appears in a first-private clause. This is expected to be used
5411 /// only with directives that start with 'target'.
5412 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5413 unsigned CurrentModifiers) {
5414 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5415
5416 // A first private variable captured by reference will use only the
5417 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5418 // declaration is known as first-private in this handler.
5419 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5420 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5421 MappableExprsHandler::OMP_MAP_TO;
5422
5423 // We didn't modify anything.
5424 return CurrentModifiers;
5425 }
5426
Samuel Antao86ace552016-04-27 22:40:57 +00005427public:
5428 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00005429 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00005430 // Extract firstprivate clause information.
5431 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5432 for (const auto *D : C->varlists())
5433 FirstPrivateDecls.insert(
5434 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00005435 // Extract device pointer clause information.
5436 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5437 for (auto L : C->component_lists())
5438 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00005439 }
Samuel Antao86ace552016-04-27 22:40:57 +00005440
5441 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00005442 /// types for the extracted mappable expressions. Also, for each item that
5443 /// relates with a device pointer, a pair of the relevant declaration and
5444 /// index where it occurs is appended to the device pointers info array.
5445 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005446 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5447 MapFlagsArrayTy &Types) const {
5448 BasePointers.clear();
5449 Pointers.clear();
5450 Sizes.clear();
5451 Types.clear();
5452
5453 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00005454 /// Kind that defines how a device pointer has to be returned.
5455 enum ReturnPointerKind {
5456 // Don't have to return any pointer.
5457 RPK_None,
5458 // Pointer is the base of the declaration.
5459 RPK_Base,
5460 // Pointer is a member of the base declaration - 'this'
5461 RPK_Member,
5462 // Pointer is a reference and a member of the base declaration - 'this'
5463 RPK_MemberReference,
5464 };
Samuel Antao86ace552016-04-27 22:40:57 +00005465 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00005466 OpenMPMapClauseKind MapType;
5467 OpenMPMapClauseKind MapTypeModifier;
5468 ReturnPointerKind ReturnDevicePointer;
5469
5470 MapInfo()
5471 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5472 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00005473 MapInfo(
5474 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5475 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5476 ReturnPointerKind ReturnDevicePointer)
5477 : Components(Components), MapType(MapType),
5478 MapTypeModifier(MapTypeModifier),
5479 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00005480 };
5481
5482 // We have to process the component lists that relate with the same
5483 // declaration in a single chunk so that we can generate the map flags
5484 // correctly. Therefore, we organize all lists in a map.
5485 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00005486
5487 // Helper function to fill the information map for the different supported
5488 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00005489 auto &&InfoGen = [&Info](
5490 const ValueDecl *D,
5491 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5492 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005493 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005494 const ValueDecl *VD =
5495 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5496 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5497 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00005498
Paul Robinson78fb1322016-08-01 22:12:46 +00005499 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005500 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005501 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005502 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5503 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005504 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005505 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005506 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5507 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005508 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005509 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005510 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5511 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00005512
Samuel Antaocc10b852016-07-28 14:23:26 +00005513 // Look at the use_device_ptr clause information and mark the existing map
5514 // entries as such. If there is no map information for an entry in the
5515 // use_device_ptr list, we create one with map type 'alloc' and zero size
5516 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00005517 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005518 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00005519 for (auto L : C->component_lists()) {
5520 assert(!L.second.empty() && "Not expecting empty list of components!");
5521 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5522 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5523 auto *IE = L.second.back().getAssociatedExpression();
5524 // If the first component is a member expression, we have to look into
5525 // 'this', which maps to null in the map of map information. Otherwise
5526 // look directly for the information.
5527 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5528
5529 // We potentially have map information for this declaration already.
5530 // Look for the first set of components that refer to it.
5531 if (It != Info.end()) {
5532 auto CI = std::find_if(
5533 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5534 return MI.Components.back().getAssociatedDeclaration() == VD;
5535 });
5536 // If we found a map entry, signal that the pointer has to be returned
5537 // and move on to the next declaration.
5538 if (CI != It->second.end()) {
5539 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5540 ? (VD->getType()->isReferenceType()
5541 ? MapInfo::RPK_MemberReference
5542 : MapInfo::RPK_Member)
5543 : MapInfo::RPK_Base;
5544 continue;
5545 }
5546 }
5547
5548 // We didn't find any match in our map information - generate a zero
5549 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00005550 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00005551 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00005552 this->CGF
5553 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00005554 .getScalarVal();
5555 BasePointers.push_back({Ptr, VD});
5556 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00005557 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00005558 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5559 }
5560
Samuel Antao86ace552016-04-27 22:40:57 +00005561 for (auto &M : Info) {
5562 // We need to know when we generate information for the first component
5563 // associated with a capture, because the mapping flags depend on it.
5564 bool IsFirstComponentList = true;
5565 for (MapInfo &L : M.second) {
5566 assert(!L.Components.empty() &&
5567 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00005568
5569 // Remember the current base pointer index.
5570 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00005571 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00005572 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5573 L.Components, BasePointers, Pointers,
5574 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00005575
5576 // If this entry relates with a device pointer, set the relevant
5577 // declaration and add the 'return pointer' flag.
5578 if (IsFirstComponentList &&
5579 L.ReturnDevicePointer != MapInfo::RPK_None) {
5580 // If the pointer is not the base of the map, we need to skip the
5581 // base. If it is a reference in a member field, we also need to skip
5582 // the map of the reference.
5583 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5584 ++CurrentBasePointersIdx;
5585 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5586 ++CurrentBasePointersIdx;
5587 }
5588 assert(BasePointers.size() > CurrentBasePointersIdx &&
5589 "Unexpected number of mapped base pointers.");
5590
5591 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5592 assert(RelevantVD &&
5593 "No relevant declaration related with device pointer??");
5594
5595 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5596 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5597 }
Samuel Antao86ace552016-04-27 22:40:57 +00005598 IsFirstComponentList = false;
5599 }
5600 }
5601 }
5602
5603 /// \brief Generate the base pointers, section pointers, sizes and map types
5604 /// associated to a given capture.
5605 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00005606 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005607 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005608 MapValuesArrayTy &Pointers,
5609 MapValuesArrayTy &Sizes,
5610 MapFlagsArrayTy &Types) const {
5611 assert(!Cap->capturesVariableArrayType() &&
5612 "Not expecting to generate map info for a variable array type!");
5613
5614 BasePointers.clear();
5615 Pointers.clear();
5616 Sizes.clear();
5617 Types.clear();
5618
Samuel Antao6890b092016-07-28 14:25:09 +00005619 // We need to know when we generating information for the first component
5620 // associated with a capture, because the mapping flags depend on it.
5621 bool IsFirstComponentList = true;
5622
Samuel Antao86ace552016-04-27 22:40:57 +00005623 const ValueDecl *VD =
5624 Cap->capturesThis()
5625 ? nullptr
5626 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5627
Samuel Antao6890b092016-07-28 14:25:09 +00005628 // If this declaration appears in a is_device_ptr clause we just have to
5629 // pass the pointer by value. If it is a reference to a declaration, we just
5630 // pass its value, otherwise, if it is a member expression, we need to map
5631 // 'to' the field.
5632 if (!VD) {
5633 auto It = DevPointersMap.find(VD);
5634 if (It != DevPointersMap.end()) {
5635 for (auto L : It->second) {
5636 generateInfoForComponentList(
5637 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5638 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5639 IsFirstComponentList = false;
5640 }
5641 return;
5642 }
5643 } else if (DevPointersMap.count(VD)) {
5644 BasePointers.push_back({Arg, VD});
5645 Pointers.push_back(Arg);
5646 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5647 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5648 return;
5649 }
5650
Paul Robinson78fb1322016-08-01 22:12:46 +00005651 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005652 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00005653 for (auto L : C->decl_component_lists(VD)) {
5654 assert(L.first == VD &&
5655 "We got information for the wrong declaration??");
5656 assert(!L.second.empty() &&
5657 "Not expecting declaration with no component lists.");
5658 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5659 L.second, BasePointers, Pointers, Sizes,
5660 Types, IsFirstComponentList);
5661 IsFirstComponentList = false;
5662 }
5663
5664 return;
5665 }
Samuel Antaod486f842016-05-26 16:53:38 +00005666
5667 /// \brief Generate the default map information for a given capture \a CI,
5668 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00005669 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5670 const FieldDecl &RI, llvm::Value *CV,
5671 MapBaseValuesArrayTy &CurBasePointers,
5672 MapValuesArrayTy &CurPointers,
5673 MapValuesArrayTy &CurSizes,
5674 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00005675
5676 // Do the default mapping.
5677 if (CI.capturesThis()) {
5678 CurBasePointers.push_back(CV);
5679 CurPointers.push_back(CV);
5680 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5681 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5682 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00005683 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00005684 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005685 CurBasePointers.push_back(CV);
5686 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00005687 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005688 // We have to signal to the runtime captures passed by value that are
5689 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00005690 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00005691 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5692 } else {
5693 // Pointers are implicitly mapped with a zero size and no flags
5694 // (other than first map that is added for all implicit maps).
5695 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00005696 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5697 }
5698 } else {
5699 assert(CI.capturesVariable() && "Expected captured reference.");
5700 CurBasePointers.push_back(CV);
5701 CurPointers.push_back(CV);
5702
5703 const ReferenceType *PtrTy =
5704 cast<ReferenceType>(RI.getType().getTypePtr());
5705 QualType ElementType = PtrTy->getPointeeType();
5706 CurSizes.push_back(CGF.getTypeSize(ElementType));
5707 // The default map type for a scalar/complex type is 'to' because by
5708 // default the value doesn't have to be retrieved. For an aggregate
5709 // type, the default is 'tofrom'.
5710 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00005711 ? (OMP_MAP_TO | OMP_MAP_FROM)
5712 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00005713
5714 // If we have a capture by reference we may need to add the private
5715 // pointer flag if the base declaration shows in some first-private
5716 // clause.
5717 CurMapTypes.back() =
5718 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5719 }
5720 // Every default map produces a single argument, so, it is always the
5721 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00005722 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00005723 }
Samuel Antao86ace552016-04-27 22:40:57 +00005724};
Samuel Antaodf158d52016-04-27 22:58:19 +00005725
5726enum OpenMPOffloadingReservedDeviceIDs {
5727 /// \brief Device ID if the device was not defined, runtime should get it
5728 /// from environment variables in the spec.
5729 OMP_DEVICEID_UNDEF = -1,
5730};
5731} // anonymous namespace
5732
5733/// \brief Emit the arrays used to pass the captures and map information to the
5734/// offloading runtime library. If there is no map or capture information,
5735/// return nullptr by reference.
5736static void
Samuel Antaocc10b852016-07-28 14:23:26 +00005737emitOffloadingArrays(CodeGenFunction &CGF,
5738 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00005739 MappableExprsHandler::MapValuesArrayTy &Pointers,
5740 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00005741 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5742 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005743 auto &CGM = CGF.CGM;
5744 auto &Ctx = CGF.getContext();
5745
Samuel Antaocc10b852016-07-28 14:23:26 +00005746 // Reset the array information.
5747 Info.clearArrayInfo();
5748 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00005749
Samuel Antaocc10b852016-07-28 14:23:26 +00005750 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005751 // Detect if we have any capture size requiring runtime evaluation of the
5752 // size so that a constant array could be eventually used.
5753 bool hasRuntimeEvaluationCaptureSize = false;
5754 for (auto *S : Sizes)
5755 if (!isa<llvm::Constant>(S)) {
5756 hasRuntimeEvaluationCaptureSize = true;
5757 break;
5758 }
5759
Samuel Antaocc10b852016-07-28 14:23:26 +00005760 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00005761 QualType PointerArrayType =
5762 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5763 /*IndexTypeQuals=*/0);
5764
Samuel Antaocc10b852016-07-28 14:23:26 +00005765 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005766 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00005767 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005768 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5769
5770 // If we don't have any VLA types or other types that require runtime
5771 // evaluation, we can use a constant array for the map sizes, otherwise we
5772 // need to fill up the arrays as we do for the pointers.
5773 if (hasRuntimeEvaluationCaptureSize) {
5774 QualType SizeArrayType = Ctx.getConstantArrayType(
5775 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5776 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00005777 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005778 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5779 } else {
5780 // We expect all the sizes to be constant, so we collect them to create
5781 // a constant array.
5782 SmallVector<llvm::Constant *, 16> ConstSizes;
5783 for (auto S : Sizes)
5784 ConstSizes.push_back(cast<llvm::Constant>(S));
5785
5786 auto *SizesArrayInit = llvm::ConstantArray::get(
5787 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5788 auto *SizesArrayGbl = new llvm::GlobalVariable(
5789 CGM.getModule(), SizesArrayInit->getType(),
5790 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5791 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005792 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005793 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005794 }
5795
5796 // The map types are always constant so we don't need to generate code to
5797 // fill arrays. Instead, we create an array constant.
5798 llvm::Constant *MapTypesArrayInit =
5799 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5800 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5801 CGM.getModule(), MapTypesArrayInit->getType(),
5802 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5803 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005804 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005805 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005806
Samuel Antaocc10b852016-07-28 14:23:26 +00005807 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5808 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00005809 if (BPVal->getType()->isPointerTy())
5810 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5811 else {
5812 assert(BPVal->getType()->isIntegerTy() &&
5813 "If not a pointer, the value type must be an integer.");
5814 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5815 }
5816 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005817 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5818 Info.BasePointersArray, 0, i);
Samuel Antaodf158d52016-04-27 22:58:19 +00005819 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5820 CGF.Builder.CreateStore(BPVal, BPAddr);
5821
Samuel Antaocc10b852016-07-28 14:23:26 +00005822 if (Info.requiresDevicePointerInfo())
5823 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
5824 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
5825
Samuel Antaodf158d52016-04-27 22:58:19 +00005826 llvm::Value *PVal = Pointers[i];
5827 if (PVal->getType()->isPointerTy())
5828 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5829 else {
5830 assert(PVal->getType()->isIntegerTy() &&
5831 "If not a pointer, the value type must be an integer.");
5832 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5833 }
5834 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005835 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5836 Info.PointersArray, 0, i);
Samuel Antaodf158d52016-04-27 22:58:19 +00005837 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5838 CGF.Builder.CreateStore(PVal, PAddr);
5839
5840 if (hasRuntimeEvaluationCaptureSize) {
5841 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005842 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5843 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005844 /*Idx0=*/0,
5845 /*Idx1=*/i);
5846 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5847 CGF.Builder.CreateStore(
5848 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5849 SAddr);
5850 }
5851 }
5852 }
5853}
5854/// \brief Emit the arguments to be passed to the runtime library based on the
5855/// arrays of pointers, sizes and map types.
5856static void emitOffloadingArraysArgument(
5857 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5858 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005859 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005860 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00005861 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005862 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005863 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5864 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005865 /*Idx0=*/0, /*Idx1=*/0);
5866 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005867 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5868 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005869 /*Idx0=*/0,
5870 /*Idx1=*/0);
5871 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005872 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005873 /*Idx0=*/0, /*Idx1=*/0);
5874 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005875 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
5876 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005877 /*Idx0=*/0,
5878 /*Idx1=*/0);
5879 } else {
5880 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5881 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5882 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5883 MapTypesArrayArg =
5884 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
5885 }
Samuel Antao86ace552016-04-27 22:40:57 +00005886}
5887
Samuel Antaobed3c462015-10-02 16:14:20 +00005888void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
5889 const OMPExecutableDirective &D,
5890 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00005891 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00005892 const Expr *IfCond, const Expr *Device,
5893 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005894 if (!CGF.HaveInsertPoint())
5895 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00005896
Samuel Antaoee8fb302016-01-06 13:42:12 +00005897 assert(OutlinedFn && "Invalid outlined function!");
5898
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005899 auto &Ctx = CGF.getContext();
5900
Samuel Antao86ace552016-04-27 22:40:57 +00005901 // Fill up the arrays with all the captured variables.
5902 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00005903 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00005904 MappableExprsHandler::MapValuesArrayTy Pointers;
5905 MappableExprsHandler::MapValuesArrayTy Sizes;
5906 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00005907
Samuel Antaocc10b852016-07-28 14:23:26 +00005908 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00005909 MappableExprsHandler::MapValuesArrayTy CurPointers;
5910 MappableExprsHandler::MapValuesArrayTy CurSizes;
5911 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
5912
Samuel Antaod486f842016-05-26 16:53:38 +00005913 // Get mappable expression information.
5914 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005915
5916 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5917 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00005918 auto CV = CapturedVars.begin();
5919 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
5920 CE = CS.capture_end();
5921 CI != CE; ++CI, ++RI, ++CV) {
5922 StringRef Name;
5923 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00005924
Samuel Antao86ace552016-04-27 22:40:57 +00005925 CurBasePointers.clear();
5926 CurPointers.clear();
5927 CurSizes.clear();
5928 CurMapTypes.clear();
5929
5930 // VLA sizes are passed to the outlined region by copy and do not have map
5931 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00005932 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00005933 CurBasePointers.push_back(*CV);
5934 CurPointers.push_back(*CV);
5935 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005936 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00005937 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
5938 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005939 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00005940 // If we have any information in the map clause, we use it, otherwise we
5941 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00005942 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005943 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00005944 if (CurBasePointers.empty())
5945 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
5946 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00005947 }
Samuel Antao86ace552016-04-27 22:40:57 +00005948 // We expect to have at least an element of information for this capture.
5949 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
5950 assert(CurBasePointers.size() == CurPointers.size() &&
5951 CurBasePointers.size() == CurSizes.size() &&
5952 CurBasePointers.size() == CurMapTypes.size() &&
5953 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005954
Samuel Antao86ace552016-04-27 22:40:57 +00005955 // The kernel args are always the first elements of the base pointers
5956 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00005957 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00005958 // We need to append the results of this capture to what we already have.
5959 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
5960 Pointers.append(CurPointers.begin(), CurPointers.end());
5961 Sizes.append(CurSizes.begin(), CurSizes.end());
5962 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00005963 }
5964
5965 // Keep track on whether the host function has to be executed.
5966 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005967 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005968 auto OffloadError = CGF.MakeAddrLValue(
5969 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
5970 OffloadErrorQType);
5971 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
5972 OffloadError);
5973
5974 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antaodf158d52016-04-27 22:58:19 +00005975 auto &&ThenGen = [&Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
5976 OutlinedFnID, OffloadError, OffloadErrorQType,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005977 &D](CodeGenFunction &CGF, PrePostActionTy &) {
5978 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00005979 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00005980 TargetDataInfo Info;
5981 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
5982 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
5983 Info.PointersArray, Info.SizesArray,
5984 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00005985
5986 // On top of the arrays that were filled up, the target offloading call
5987 // takes as arguments the device id as well as the host pointer. The host
5988 // pointer is used by the runtime library to identify the current target
5989 // region, so it only has to be unique and not necessarily point to
5990 // anything. It could be the pointer to the outlined function that
5991 // implements the target region, but we aren't using that so that the
5992 // compiler doesn't need to keep that, and could therefore inline the host
5993 // function if proven worthwhile during optimization.
5994
Samuel Antaoee8fb302016-01-06 13:42:12 +00005995 // From this point on, we need to have an ID of the target region defined.
5996 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005997
5998 // Emit device ID if any.
5999 llvm::Value *DeviceID;
6000 if (Device)
6001 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006002 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006003 else
6004 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6005
Samuel Antaodf158d52016-04-27 22:58:19 +00006006 // Emit the number of elements in the offloading arrays.
6007 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6008
Samuel Antaob68e2db2016-03-03 16:20:23 +00006009 // Return value of the runtime offloading call.
6010 llvm::Value *Return;
6011
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006012 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
6013 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006014
6015 // If we have NumTeams defined this means that we have an enclosed teams
6016 // region. Therefore we also expect to have ThreadLimit defined. These two
6017 // values should be defined in the presence of a teams directive, regardless
6018 // of having any clauses associated. If the user is using teams but no
6019 // clauses, these two values will be the default that should be passed to
6020 // the runtime library - a 32-bit integer with the value zero.
6021 if (NumTeams) {
6022 assert(ThreadLimit && "Thread limit expression should be available along "
6023 "with number of teams.");
6024 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006025 DeviceID, OutlinedFnID,
6026 PointerNum, Info.BasePointersArray,
6027 Info.PointersArray, Info.SizesArray,
6028 Info.MapTypesArray, NumTeams,
6029 ThreadLimit};
Samuel Antaob68e2db2016-03-03 16:20:23 +00006030 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006031 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006032 } else {
6033 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006034 DeviceID, OutlinedFnID,
6035 PointerNum, Info.BasePointersArray,
6036 Info.PointersArray, Info.SizesArray,
6037 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006038 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00006039 OffloadingArgs);
6040 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006041
6042 CGF.EmitStoreOfScalar(Return, OffloadError);
6043 };
6044
Samuel Antaoee8fb302016-01-06 13:42:12 +00006045 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006046 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6047 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00006048 OffloadError);
6049 };
6050
6051 // If we have a target function ID it means that we need to support
6052 // offloading, otherwise, just execute on the host. We need to execute on host
6053 // regardless of the conditional in the if clause if, e.g., the user do not
6054 // specify target triples.
6055 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006056 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00006057 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006058 else {
6059 RegionCodeGenTy ThenRCG(ThenGen);
6060 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006061 }
6062 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006063 RegionCodeGenTy ElseRCG(ElseGen);
6064 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006065 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006066
6067 // Check the error code and execute the host version if required.
6068 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6069 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6070 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6071 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6072 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6073
6074 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00006075 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00006076 CGF.EmitBranch(OffloadContBlock);
6077
6078 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006079}
Samuel Antaoee8fb302016-01-06 13:42:12 +00006080
6081void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6082 StringRef ParentName) {
6083 if (!S)
6084 return;
6085
6086 // If we find a OMP target directive, codegen the outline function and
6087 // register the result.
6088 // FIXME: Add other directives with target when they become supported.
6089 bool isTargetDirective = isa<OMPTargetDirective>(S);
6090
6091 if (isTargetDirective) {
6092 auto *E = cast<OMPExecutableDirective>(S);
6093 unsigned DeviceID;
6094 unsigned FileID;
6095 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006096 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006097 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006098
6099 // Is this a target region that should not be emitted as an entry point? If
6100 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00006101 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6102 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00006103 return;
6104
6105 llvm::Function *Fn;
6106 llvm::Constant *Addr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006107 std::tie(Fn, Addr) =
6108 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
6109 CGM, cast<OMPTargetDirective>(*E), ParentName,
6110 /*isOffloadEntry=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006111 assert(Fn && Addr && "Target region emission failed.");
6112 return;
6113 }
6114
6115 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00006116 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00006117 return;
6118
6119 scanForTargetRegionsFunctions(
6120 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6121 ParentName);
6122 return;
6123 }
6124
6125 // If this is a lambda function, look into its body.
6126 if (auto *L = dyn_cast<LambdaExpr>(S))
6127 S = L->getBody();
6128
6129 // Keep looking for target regions recursively.
6130 for (auto *II : S->children())
6131 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006132}
6133
6134bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6135 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6136
6137 // If emitting code for the host, we do not process FD here. Instead we do
6138 // the normal code generation.
6139 if (!CGM.getLangOpts().OpenMPIsDevice)
6140 return false;
6141
6142 // Try to detect target regions in the function.
6143 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6144
6145 // We should not emit any function othen that the ones created during the
6146 // scanning. Therefore, we signal that this function is completely dealt
6147 // with.
6148 return true;
6149}
6150
6151bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6152 if (!CGM.getLangOpts().OpenMPIsDevice)
6153 return false;
6154
6155 // Check if there are Ctors/Dtors in this declaration and look for target
6156 // regions in it. We use the complete variant to produce the kernel name
6157 // mangling.
6158 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6159 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6160 for (auto *Ctor : RD->ctors()) {
6161 StringRef ParentName =
6162 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6163 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6164 }
6165 auto *Dtor = RD->getDestructor();
6166 if (Dtor) {
6167 StringRef ParentName =
6168 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6169 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6170 }
6171 }
6172
6173 // If we are in target mode we do not emit any global (declare target is not
6174 // implemented yet). Therefore we signal that GD was processed in this case.
6175 return true;
6176}
6177
6178bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6179 auto *VD = GD.getDecl();
6180 if (isa<FunctionDecl>(VD))
6181 return emitTargetFunctions(GD);
6182
6183 return emitTargetGlobalVariable(GD);
6184}
6185
6186llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6187 // If we have offloading in the current module, we need to emit the entries
6188 // now and register the offloading descriptor.
6189 createOffloadEntriesAndInfoMetadata();
6190
6191 // Create and register the offloading binary descriptors. This is the main
6192 // entity that captures all the information about offloading in the current
6193 // compilation unit.
6194 return createOffloadingBinaryDescriptorRegistration();
6195}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006196
6197void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6198 const OMPExecutableDirective &D,
6199 SourceLocation Loc,
6200 llvm::Value *OutlinedFn,
6201 ArrayRef<llvm::Value *> CapturedVars) {
6202 if (!CGF.HaveInsertPoint())
6203 return;
6204
6205 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6206 CodeGenFunction::RunCleanupsScope Scope(CGF);
6207
6208 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6209 llvm::Value *Args[] = {
6210 RTLoc,
6211 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6212 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6213 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6214 RealArgs.append(std::begin(Args), std::end(Args));
6215 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6216
6217 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6218 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6219}
6220
6221void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00006222 const Expr *NumTeams,
6223 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006224 SourceLocation Loc) {
6225 if (!CGF.HaveInsertPoint())
6226 return;
6227
6228 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6229
Carlo Bertollic6872252016-04-04 15:55:02 +00006230 llvm::Value *NumTeamsVal =
6231 (NumTeams)
6232 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6233 CGF.CGM.Int32Ty, /* isSigned = */ true)
6234 : CGF.Builder.getInt32(0);
6235
6236 llvm::Value *ThreadLimitVal =
6237 (ThreadLimit)
6238 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6239 CGF.CGM.Int32Ty, /* isSigned = */ true)
6240 : CGF.Builder.getInt32(0);
6241
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006242 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00006243 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6244 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006245 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6246 PushNumTeamsArgs);
6247}
Samuel Antaodf158d52016-04-27 22:58:19 +00006248
Samuel Antaocc10b852016-07-28 14:23:26 +00006249void CGOpenMPRuntime::emitTargetDataCalls(
6250 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6251 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006252 if (!CGF.HaveInsertPoint())
6253 return;
6254
Samuel Antaocc10b852016-07-28 14:23:26 +00006255 // Action used to replace the default codegen action and turn privatization
6256 // off.
6257 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00006258
6259 // Generate the code for the opening of the data environment. Capture all the
6260 // arguments of the runtime call by reference because they are used in the
6261 // closing of the region.
Samuel Antaocc10b852016-07-28 14:23:26 +00006262 auto &&BeginThenGen = [&D, &CGF, Device, &Info, &CodeGen, &NoPrivAction](
6263 CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006264 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006265 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00006266 MappableExprsHandler::MapValuesArrayTy Pointers;
6267 MappableExprsHandler::MapValuesArrayTy Sizes;
6268 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6269
6270 // Get map clause information.
6271 MappableExprsHandler MCHandler(D, CGF);
6272 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00006273
6274 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006275 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006276
6277 llvm::Value *BasePointersArrayArg = nullptr;
6278 llvm::Value *PointersArrayArg = nullptr;
6279 llvm::Value *SizesArrayArg = nullptr;
6280 llvm::Value *MapTypesArrayArg = nullptr;
6281 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006282 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006283
6284 // Emit device ID if any.
6285 llvm::Value *DeviceID = nullptr;
6286 if (Device)
6287 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6288 CGF.Int32Ty, /*isSigned=*/true);
6289 else
6290 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6291
6292 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006293 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006294
6295 llvm::Value *OffloadingArgs[] = {
6296 DeviceID, PointerNum, BasePointersArrayArg,
6297 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6298 auto &RT = CGF.CGM.getOpenMPRuntime();
6299 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6300 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00006301
6302 // If device pointer privatization is required, emit the body of the region
6303 // here. It will have to be duplicated: with and without privatization.
6304 if (!Info.CaptureDeviceAddrMap.empty())
6305 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006306 };
6307
6308 // Generate code for the closing of the data region.
Samuel Antaocc10b852016-07-28 14:23:26 +00006309 auto &&EndThenGen = [&CGF, Device, &Info](CodeGenFunction &CGF,
6310 PrePostActionTy &) {
6311 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00006312
6313 llvm::Value *BasePointersArrayArg = nullptr;
6314 llvm::Value *PointersArrayArg = nullptr;
6315 llvm::Value *SizesArrayArg = nullptr;
6316 llvm::Value *MapTypesArrayArg = nullptr;
6317 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006318 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006319
6320 // Emit device ID if any.
6321 llvm::Value *DeviceID = nullptr;
6322 if (Device)
6323 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6324 CGF.Int32Ty, /*isSigned=*/true);
6325 else
6326 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6327
6328 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006329 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006330
6331 llvm::Value *OffloadingArgs[] = {
6332 DeviceID, PointerNum, BasePointersArrayArg,
6333 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6334 auto &RT = CGF.CGM.getOpenMPRuntime();
6335 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6336 OffloadingArgs);
6337 };
6338
Samuel Antaocc10b852016-07-28 14:23:26 +00006339 // If we need device pointer privatization, we need to emit the body of the
6340 // region with no privatization in the 'else' branch of the conditional.
6341 // Otherwise, we don't have to do anything.
6342 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6343 PrePostActionTy &) {
6344 if (!Info.CaptureDeviceAddrMap.empty()) {
6345 CodeGen.setAction(NoPrivAction);
6346 CodeGen(CGF);
6347 }
6348 };
6349
6350 // We don't have to do anything to close the region if the if clause evaluates
6351 // to false.
6352 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00006353
6354 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006355 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006356 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006357 RegionCodeGenTy RCG(BeginThenGen);
6358 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006359 }
6360
Samuel Antaocc10b852016-07-28 14:23:26 +00006361 // If we don't require privatization of device pointers, we emit the body in
6362 // between the runtime calls. This avoids duplicating the body code.
6363 if (Info.CaptureDeviceAddrMap.empty()) {
6364 CodeGen.setAction(NoPrivAction);
6365 CodeGen(CGF);
6366 }
Samuel Antaodf158d52016-04-27 22:58:19 +00006367
6368 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006369 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006370 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006371 RegionCodeGenTy RCG(EndThenGen);
6372 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006373 }
6374}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006375
Samuel Antao8d2d7302016-05-26 18:30:22 +00006376void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00006377 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6378 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006379 if (!CGF.HaveInsertPoint())
6380 return;
6381
Samuel Antao8dd66282016-04-27 23:14:30 +00006382 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00006383 isa<OMPTargetExitDataDirective>(D) ||
6384 isa<OMPTargetUpdateDirective>(D)) &&
6385 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00006386
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006387 // Generate the code for the opening of the data environment.
6388 auto &&ThenGen = [&D, &CGF, Device](CodeGenFunction &CGF, PrePostActionTy &) {
6389 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006390 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006391 MappableExprsHandler::MapValuesArrayTy Pointers;
6392 MappableExprsHandler::MapValuesArrayTy Sizes;
6393 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6394
6395 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00006396 MappableExprsHandler MEHandler(D, CGF);
6397 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006398
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006399 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006400 TargetDataInfo Info;
6401 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6402 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6403 Info.PointersArray, Info.SizesArray,
6404 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006405
6406 // Emit device ID if any.
6407 llvm::Value *DeviceID = nullptr;
6408 if (Device)
6409 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6410 CGF.Int32Ty, /*isSigned=*/true);
6411 else
6412 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6413
6414 // Emit the number of elements in the offloading arrays.
6415 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6416
6417 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006418 DeviceID, PointerNum, Info.BasePointersArray,
6419 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00006420
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006421 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00006422 // Select the right runtime function call for each expected standalone
6423 // directive.
6424 OpenMPRTLFunction RTLFn;
6425 switch (D.getDirectiveKind()) {
6426 default:
6427 llvm_unreachable("Unexpected standalone target data directive.");
6428 break;
6429 case OMPD_target_enter_data:
6430 RTLFn = OMPRTL__tgt_target_data_begin;
6431 break;
6432 case OMPD_target_exit_data:
6433 RTLFn = OMPRTL__tgt_target_data_end;
6434 break;
6435 case OMPD_target_update:
6436 RTLFn = OMPRTL__tgt_target_data_update;
6437 break;
6438 }
6439 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006440 };
6441
6442 // In the event we get an if clause, we don't have to take any action on the
6443 // else side.
6444 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6445
6446 if (IfCond) {
6447 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6448 } else {
6449 RegionCodeGenTy ThenGenRCG(ThenGen);
6450 ThenGenRCG(CGF);
6451 }
6452}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006453
6454namespace {
6455 /// Kind of parameter in a function with 'declare simd' directive.
6456 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6457 /// Attribute set of the parameter.
6458 struct ParamAttrTy {
6459 ParamKindTy Kind = Vector;
6460 llvm::APSInt StrideOrArg;
6461 llvm::APSInt Alignment;
6462 };
6463} // namespace
6464
6465static unsigned evaluateCDTSize(const FunctionDecl *FD,
6466 ArrayRef<ParamAttrTy> ParamAttrs) {
6467 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6468 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6469 // of that clause. The VLEN value must be power of 2.
6470 // In other case the notion of the function`s "characteristic data type" (CDT)
6471 // is used to compute the vector length.
6472 // CDT is defined in the following order:
6473 // a) For non-void function, the CDT is the return type.
6474 // b) If the function has any non-uniform, non-linear parameters, then the
6475 // CDT is the type of the first such parameter.
6476 // c) If the CDT determined by a) or b) above is struct, union, or class
6477 // type which is pass-by-value (except for the type that maps to the
6478 // built-in complex data type), the characteristic data type is int.
6479 // d) If none of the above three cases is applicable, the CDT is int.
6480 // The VLEN is then determined based on the CDT and the size of vector
6481 // register of that ISA for which current vector version is generated. The
6482 // VLEN is computed using the formula below:
6483 // VLEN = sizeof(vector_register) / sizeof(CDT),
6484 // where vector register size specified in section 3.2.1 Registers and the
6485 // Stack Frame of original AMD64 ABI document.
6486 QualType RetType = FD->getReturnType();
6487 if (RetType.isNull())
6488 return 0;
6489 ASTContext &C = FD->getASTContext();
6490 QualType CDT;
6491 if (!RetType.isNull() && !RetType->isVoidType())
6492 CDT = RetType;
6493 else {
6494 unsigned Offset = 0;
6495 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6496 if (ParamAttrs[Offset].Kind == Vector)
6497 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6498 ++Offset;
6499 }
6500 if (CDT.isNull()) {
6501 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6502 if (ParamAttrs[I + Offset].Kind == Vector) {
6503 CDT = FD->getParamDecl(I)->getType();
6504 break;
6505 }
6506 }
6507 }
6508 }
6509 if (CDT.isNull())
6510 CDT = C.IntTy;
6511 CDT = CDT->getCanonicalTypeUnqualified();
6512 if (CDT->isRecordType() || CDT->isUnionType())
6513 CDT = C.IntTy;
6514 return C.getTypeSize(CDT);
6515}
6516
6517static void
6518emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00006519 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006520 ArrayRef<ParamAttrTy> ParamAttrs,
6521 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6522 struct ISADataTy {
6523 char ISA;
6524 unsigned VecRegSize;
6525 };
6526 ISADataTy ISAData[] = {
6527 {
6528 'b', 128
6529 }, // SSE
6530 {
6531 'c', 256
6532 }, // AVX
6533 {
6534 'd', 256
6535 }, // AVX2
6536 {
6537 'e', 512
6538 }, // AVX512
6539 };
6540 llvm::SmallVector<char, 2> Masked;
6541 switch (State) {
6542 case OMPDeclareSimdDeclAttr::BS_Undefined:
6543 Masked.push_back('N');
6544 Masked.push_back('M');
6545 break;
6546 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6547 Masked.push_back('N');
6548 break;
6549 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6550 Masked.push_back('M');
6551 break;
6552 }
6553 for (auto Mask : Masked) {
6554 for (auto &Data : ISAData) {
6555 SmallString<256> Buffer;
6556 llvm::raw_svector_ostream Out(Buffer);
6557 Out << "_ZGV" << Data.ISA << Mask;
6558 if (!VLENVal) {
6559 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6560 evaluateCDTSize(FD, ParamAttrs));
6561 } else
6562 Out << VLENVal;
6563 for (auto &ParamAttr : ParamAttrs) {
6564 switch (ParamAttr.Kind){
6565 case LinearWithVarStride:
6566 Out << 's' << ParamAttr.StrideOrArg;
6567 break;
6568 case Linear:
6569 Out << 'l';
6570 if (!!ParamAttr.StrideOrArg)
6571 Out << ParamAttr.StrideOrArg;
6572 break;
6573 case Uniform:
6574 Out << 'u';
6575 break;
6576 case Vector:
6577 Out << 'v';
6578 break;
6579 }
6580 if (!!ParamAttr.Alignment)
6581 Out << 'a' << ParamAttr.Alignment;
6582 }
6583 Out << '_' << Fn->getName();
6584 Fn->addFnAttr(Out.str());
6585 }
6586 }
6587}
6588
6589void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6590 llvm::Function *Fn) {
6591 ASTContext &C = CGM.getContext();
6592 FD = FD->getCanonicalDecl();
6593 // Map params to their positions in function decl.
6594 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6595 if (isa<CXXMethodDecl>(FD))
6596 ParamPositions.insert({FD, 0});
6597 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00006598 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006599 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6600 ++ParamPos;
6601 }
6602 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6603 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6604 // Mark uniform parameters.
6605 for (auto *E : Attr->uniforms()) {
6606 E = E->IgnoreParenImpCasts();
6607 unsigned Pos;
6608 if (isa<CXXThisExpr>(E))
6609 Pos = ParamPositions[FD];
6610 else {
6611 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6612 ->getCanonicalDecl();
6613 Pos = ParamPositions[PVD];
6614 }
6615 ParamAttrs[Pos].Kind = Uniform;
6616 }
6617 // Get alignment info.
6618 auto NI = Attr->alignments_begin();
6619 for (auto *E : Attr->aligneds()) {
6620 E = E->IgnoreParenImpCasts();
6621 unsigned Pos;
6622 QualType ParmTy;
6623 if (isa<CXXThisExpr>(E)) {
6624 Pos = ParamPositions[FD];
6625 ParmTy = E->getType();
6626 } else {
6627 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6628 ->getCanonicalDecl();
6629 Pos = ParamPositions[PVD];
6630 ParmTy = PVD->getType();
6631 }
6632 ParamAttrs[Pos].Alignment =
6633 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6634 : llvm::APSInt::getUnsigned(
6635 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6636 .getQuantity());
6637 ++NI;
6638 }
6639 // Mark linear parameters.
6640 auto SI = Attr->steps_begin();
6641 auto MI = Attr->modifiers_begin();
6642 for (auto *E : Attr->linears()) {
6643 E = E->IgnoreParenImpCasts();
6644 unsigned Pos;
6645 if (isa<CXXThisExpr>(E))
6646 Pos = ParamPositions[FD];
6647 else {
6648 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6649 ->getCanonicalDecl();
6650 Pos = ParamPositions[PVD];
6651 }
6652 auto &ParamAttr = ParamAttrs[Pos];
6653 ParamAttr.Kind = Linear;
6654 if (*SI) {
6655 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6656 Expr::SE_AllowSideEffects)) {
6657 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6658 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6659 ParamAttr.Kind = LinearWithVarStride;
6660 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6661 ParamPositions[StridePVD->getCanonicalDecl()]);
6662 }
6663 }
6664 }
6665 }
6666 ++SI;
6667 ++MI;
6668 }
6669 llvm::APSInt VLENVal;
6670 if (const Expr *VLEN = Attr->getSimdlen())
6671 VLENVal = VLEN->EvaluateKnownConstInt(C);
6672 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6673 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6674 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6675 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6676 }
6677}
Alexey Bataev8b427062016-05-25 12:36:08 +00006678
6679namespace {
6680/// Cleanup action for doacross support.
6681class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6682public:
6683 static const int DoacrossFinArgs = 2;
6684
6685private:
6686 llvm::Value *RTLFn;
6687 llvm::Value *Args[DoacrossFinArgs];
6688
6689public:
6690 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6691 : RTLFn(RTLFn) {
6692 assert(CallArgs.size() == DoacrossFinArgs);
6693 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6694 }
6695 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6696 if (!CGF.HaveInsertPoint())
6697 return;
6698 CGF.EmitRuntimeCall(RTLFn, Args);
6699 }
6700};
6701} // namespace
6702
6703void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6704 const OMPLoopDirective &D) {
6705 if (!CGF.HaveInsertPoint())
6706 return;
6707
6708 ASTContext &C = CGM.getContext();
6709 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6710 RecordDecl *RD;
6711 if (KmpDimTy.isNull()) {
6712 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6713 // kmp_int64 lo; // lower
6714 // kmp_int64 up; // upper
6715 // kmp_int64 st; // stride
6716 // };
6717 RD = C.buildImplicitRecord("kmp_dim");
6718 RD->startDefinition();
6719 addFieldToRecordDecl(C, RD, Int64Ty);
6720 addFieldToRecordDecl(C, RD, Int64Ty);
6721 addFieldToRecordDecl(C, RD, Int64Ty);
6722 RD->completeDefinition();
6723 KmpDimTy = C.getRecordType(RD);
6724 } else
6725 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6726
6727 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6728 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6729 enum { LowerFD = 0, UpperFD, StrideFD };
6730 // Fill dims with data.
6731 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6732 // dims.upper = num_iterations;
6733 LValue UpperLVal =
6734 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6735 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6736 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6737 Int64Ty, D.getNumIterations()->getExprLoc());
6738 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6739 // dims.stride = 1;
6740 LValue StrideLVal =
6741 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6742 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6743 StrideLVal);
6744
6745 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6746 // kmp_int32 num_dims, struct kmp_dim * dims);
6747 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6748 getThreadID(CGF, D.getLocStart()),
6749 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6750 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6751 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6752
6753 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6754 CGF.EmitRuntimeCall(RTLFn, Args);
6755 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6756 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6757 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6758 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6759 llvm::makeArrayRef(FiniArgs));
6760}
6761
6762void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6763 const OMPDependClause *C) {
6764 QualType Int64Ty =
6765 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6766 const Expr *CounterVal = C->getCounterValue();
6767 assert(CounterVal);
6768 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6769 CounterVal->getType(), Int64Ty,
6770 CounterVal->getExprLoc());
6771 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6772 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6773 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6774 getThreadID(CGF, C->getLocStart()),
6775 CntAddr.getPointer()};
6776 llvm::Value *RTLFn;
6777 if (C->getDependencyKind() == OMPC_DEPEND_source)
6778 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6779 else {
6780 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6781 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6782 }
6783 CGF.EmitRuntimeCall(RTLFn, Args);
6784}
6785