blob: 27af344fae87a2c33837ab6b6f369c5e45425b82 [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);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000760 Fn->removeFnAttr(llvm::Attribute::NoInline);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000761 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000762 CodeGenFunction CGF(CGM);
763 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
764 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
765 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
766 CodeGenFunction::OMPPrivateScope Scope(CGF);
767 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
768 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
769 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
770 .getAddress();
771 });
772 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
773 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
774 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
775 .getAddress();
776 });
777 (void)Scope.Privatize();
778 CGF.EmitIgnoredExpr(CombinerInitializer);
779 Scope.ForceCleanup();
780 CGF.FinishFunction();
781 return Fn;
782}
783
784void CGOpenMPRuntime::emitUserDefinedReduction(
785 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
786 if (UDRMap.count(D) > 0)
787 return;
788 auto &C = CGM.getContext();
789 if (!In || !Out) {
790 In = &C.Idents.get("omp_in");
791 Out = &C.Idents.get("omp_out");
792 }
793 llvm::Function *Combiner = emitCombinerOrInitializer(
794 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
795 cast<VarDecl>(D->lookup(Out).front()),
796 /*IsCombiner=*/true);
797 llvm::Function *Initializer = nullptr;
798 if (auto *Init = D->getInitializer()) {
799 if (!Priv || !Orig) {
800 Priv = &C.Idents.get("omp_priv");
801 Orig = &C.Idents.get("omp_orig");
802 }
803 Initializer = emitCombinerOrInitializer(
804 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
805 cast<VarDecl>(D->lookup(Priv).front()),
806 /*IsCombiner=*/false);
807 }
808 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
809 if (CGF) {
810 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
811 Decls.second.push_back(D);
812 }
813}
814
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000815std::pair<llvm::Function *, llvm::Function *>
816CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
817 auto I = UDRMap.find(D);
818 if (I != UDRMap.end())
819 return I->second;
820 emitUserDefinedReduction(/*CGF=*/nullptr, D);
821 return UDRMap.lookup(D);
822}
823
John McCall7f416cc2015-09-08 08:05:57 +0000824// Layout information for ident_t.
825static CharUnits getIdentAlign(CodeGenModule &CGM) {
826 return CGM.getPointerAlign();
827}
828static CharUnits getIdentSize(CodeGenModule &CGM) {
829 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
830 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
831}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000832static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000833 // All the fields except the last are i32, so this works beautifully.
834 return unsigned(Field) * CharUnits::fromQuantity(4);
835}
836static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000837 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000838 const llvm::Twine &Name = "") {
839 auto Offset = getOffsetOfIdentField(Field);
840 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
841}
842
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000843llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000844 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
845 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000846 assert(ThreadIDVar->getType()->isPointerType() &&
847 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000848 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
849 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000850 bool HasCancel = false;
851 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
852 HasCancel = OPD->hasCancel();
853 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
854 HasCancel = OPSD->hasCancel();
855 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
856 HasCancel = OPFD->hasCancel();
857 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
858 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000859 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000860 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000861}
862
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000863llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
864 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000865 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
866 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
867 bool Tied, unsigned &NumberOfParts) {
868 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
869 PrePostActionTy &) {
870 auto *ThreadID = getThreadID(CGF, D.getLocStart());
871 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
872 llvm::Value *TaskArgs[] = {
873 UpLoc, ThreadID,
874 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
875 TaskTVar->getType()->castAs<PointerType>())
876 .getPointer()};
877 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
878 };
879 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
880 UntiedCodeGen);
881 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000882 assert(!ThreadIDVar->getType()->isPointerType() &&
883 "thread id variable must be of type kmp_int32 for tasks");
884 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000885 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000886 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000887 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
888 InnermostKind,
889 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000890 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000891 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
892 if (!Tied)
893 NumberOfParts = Action.getNumberOfParts();
894 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000895}
896
Alexey Bataev50b3c952016-02-19 10:38:26 +0000897Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000898 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000899 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000900 if (!Entry) {
901 if (!DefaultOpenMPPSource) {
902 // Initialize default location for psource field of ident_t structure of
903 // all ident_t objects. Format is ";file;function;line;column;;".
904 // Taken from
905 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
906 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000907 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000908 DefaultOpenMPPSource =
909 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
910 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000911
John McCall23c9dc62016-11-28 22:18:27 +0000912 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000913 auto fields = builder.beginStruct(IdentTy);
914 fields.addInt(CGM.Int32Ty, 0);
915 fields.addInt(CGM.Int32Ty, Flags);
916 fields.addInt(CGM.Int32Ty, 0);
917 fields.addInt(CGM.Int32Ty, 0);
918 fields.add(DefaultOpenMPPSource);
919 auto DefaultOpenMPLocation =
920 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
921 llvm::GlobalValue::PrivateLinkage);
922 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
923
John McCall7f416cc2015-09-08 08:05:57 +0000924 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000925 }
John McCall7f416cc2015-09-08 08:05:57 +0000926 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000927}
928
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000929llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
930 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000931 unsigned Flags) {
932 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000933 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000934 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000935 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000936 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000937
938 assert(CGF.CurFn && "No function in current CodeGenFunction.");
939
John McCall7f416cc2015-09-08 08:05:57 +0000940 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000941 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
942 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000943 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
944
Alexander Musmanc6388682014-12-15 07:07:06 +0000945 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
946 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000947 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000948 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000949 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
950 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000951 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000952 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000953 LocValue = AI;
954
955 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
956 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000957 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000958 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000959 }
960
961 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000962 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000963
Alexey Bataevf002aca2014-05-30 05:48:40 +0000964 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
965 if (OMPDebugLoc == nullptr) {
966 SmallString<128> Buffer2;
967 llvm::raw_svector_ostream OS2(Buffer2);
968 // Build debug location
969 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
970 OS2 << ";" << PLoc.getFilename() << ";";
971 if (const FunctionDecl *FD =
972 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
973 OS2 << FD->getQualifiedNameAsString();
974 }
975 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
976 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
977 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000978 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000979 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000980 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
981
John McCall7f416cc2015-09-08 08:05:57 +0000982 // Our callers always pass this to a runtime function, so for
983 // convenience, go ahead and return a naked pointer.
984 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000985}
986
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000987llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
988 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000989 assert(CGF.CurFn && "No function in current CodeGenFunction.");
990
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000991 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000992 // Check whether we've already cached a load of the thread id in this
993 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000994 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000995 if (I != OpenMPLocThreadIDMap.end()) {
996 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000997 if (ThreadID != nullptr)
998 return ThreadID;
999 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001000 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001001 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001002 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001003 // Check if this an outlined function with thread id passed as argument.
1004 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001005 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1006 // If value loaded in entry block, cache it and use it everywhere in
1007 // function.
1008 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1009 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1010 Elem.second.ThreadID = ThreadID;
1011 }
1012 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001013 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001014 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001015
1016 // This is not an outlined function region - need to call __kmpc_int32
1017 // kmpc_global_thread_num(ident_t *loc).
1018 // Generate thread id value and cache this value for use across the
1019 // function.
1020 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1021 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1022 ThreadID =
1023 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1024 emitUpdateLocation(CGF, Loc));
1025 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1026 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001027 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001028}
1029
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001030void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001031 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001032 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1033 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001034 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1035 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1036 UDRMap.erase(D);
1037 }
1038 FunctionUDRMap.erase(CGF.CurFn);
1039 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001040}
1041
1042llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001043 if (!IdentTy) {
1044 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001045 return llvm::PointerType::getUnqual(IdentTy);
1046}
1047
1048llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001049 if (!Kmpc_MicroTy) {
1050 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1051 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1052 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1053 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1054 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001055 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1056}
1057
1058llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001059CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001060 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001061 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001062 case OMPRTL__kmpc_fork_call: {
1063 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1064 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001065 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1066 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001067 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001068 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001069 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1070 break;
1071 }
1072 case OMPRTL__kmpc_global_thread_num: {
1073 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001074 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001075 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001076 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001077 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1078 break;
1079 }
Alexey Bataev97720002014-11-11 04:05:39 +00001080 case OMPRTL__kmpc_threadprivate_cached: {
1081 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1082 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1083 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1084 CGM.VoidPtrTy, CGM.SizeTy,
1085 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1086 llvm::FunctionType *FnTy =
1087 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1088 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1089 break;
1090 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001091 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001092 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1093 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001094 llvm::Type *TypeParams[] = {
1095 getIdentTyPointerTy(), CGM.Int32Ty,
1096 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1097 llvm::FunctionType *FnTy =
1098 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1099 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1100 break;
1101 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001102 case OMPRTL__kmpc_critical_with_hint: {
1103 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1104 // kmp_critical_name *crit, uintptr_t hint);
1105 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1106 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1107 CGM.IntPtrTy};
1108 llvm::FunctionType *FnTy =
1109 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1110 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1111 break;
1112 }
Alexey Bataev97720002014-11-11 04:05:39 +00001113 case OMPRTL__kmpc_threadprivate_register: {
1114 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1115 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1116 // typedef void *(*kmpc_ctor)(void *);
1117 auto KmpcCtorTy =
1118 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1119 /*isVarArg*/ false)->getPointerTo();
1120 // typedef void *(*kmpc_cctor)(void *, void *);
1121 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1122 auto KmpcCopyCtorTy =
1123 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1124 /*isVarArg*/ false)->getPointerTo();
1125 // typedef void (*kmpc_dtor)(void *);
1126 auto KmpcDtorTy =
1127 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1128 ->getPointerTo();
1129 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1130 KmpcCopyCtorTy, KmpcDtorTy};
1131 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1132 /*isVarArg*/ false);
1133 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1134 break;
1135 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001136 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001137 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1138 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001139 llvm::Type *TypeParams[] = {
1140 getIdentTyPointerTy(), CGM.Int32Ty,
1141 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1142 llvm::FunctionType *FnTy =
1143 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1144 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1145 break;
1146 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001147 case OMPRTL__kmpc_cancel_barrier: {
1148 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1149 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001150 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1151 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001152 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1153 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001154 break;
1155 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001156 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001157 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001158 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1159 llvm::FunctionType *FnTy =
1160 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1161 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1162 break;
1163 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001164 case OMPRTL__kmpc_for_static_fini: {
1165 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1166 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1167 llvm::FunctionType *FnTy =
1168 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1169 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1170 break;
1171 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001172 case OMPRTL__kmpc_push_num_threads: {
1173 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1174 // kmp_int32 num_threads)
1175 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1176 CGM.Int32Ty};
1177 llvm::FunctionType *FnTy =
1178 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1179 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1180 break;
1181 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001182 case OMPRTL__kmpc_serialized_parallel: {
1183 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1184 // global_tid);
1185 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1186 llvm::FunctionType *FnTy =
1187 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1188 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1189 break;
1190 }
1191 case OMPRTL__kmpc_end_serialized_parallel: {
1192 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1193 // global_tid);
1194 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1195 llvm::FunctionType *FnTy =
1196 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1197 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1198 break;
1199 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001200 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001201 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001202 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1203 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001204 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001205 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1206 break;
1207 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001208 case OMPRTL__kmpc_master: {
1209 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1210 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1211 llvm::FunctionType *FnTy =
1212 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1213 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1214 break;
1215 }
1216 case OMPRTL__kmpc_end_master: {
1217 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1218 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1219 llvm::FunctionType *FnTy =
1220 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1221 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1222 break;
1223 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001224 case OMPRTL__kmpc_omp_taskyield: {
1225 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1226 // int end_part);
1227 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1228 llvm::FunctionType *FnTy =
1229 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1230 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1231 break;
1232 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001233 case OMPRTL__kmpc_single: {
1234 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1235 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1236 llvm::FunctionType *FnTy =
1237 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1238 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1239 break;
1240 }
1241 case OMPRTL__kmpc_end_single: {
1242 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1243 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1244 llvm::FunctionType *FnTy =
1245 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1246 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1247 break;
1248 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001249 case OMPRTL__kmpc_omp_task_alloc: {
1250 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1251 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1252 // kmp_routine_entry_t *task_entry);
1253 assert(KmpRoutineEntryPtrTy != nullptr &&
1254 "Type kmp_routine_entry_t must be created.");
1255 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1256 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1257 // Return void * and then cast to particular kmp_task_t type.
1258 llvm::FunctionType *FnTy =
1259 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1260 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1261 break;
1262 }
1263 case OMPRTL__kmpc_omp_task: {
1264 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1265 // *new_task);
1266 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1267 CGM.VoidPtrTy};
1268 llvm::FunctionType *FnTy =
1269 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1270 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1271 break;
1272 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001273 case OMPRTL__kmpc_copyprivate: {
1274 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001275 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001276 // kmp_int32 didit);
1277 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1278 auto *CpyFnTy =
1279 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001280 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001281 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1282 CGM.Int32Ty};
1283 llvm::FunctionType *FnTy =
1284 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1285 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1286 break;
1287 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001288 case OMPRTL__kmpc_reduce: {
1289 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1290 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1291 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1292 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1293 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1294 /*isVarArg=*/false);
1295 llvm::Type *TypeParams[] = {
1296 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1297 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1298 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1299 llvm::FunctionType *FnTy =
1300 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1301 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1302 break;
1303 }
1304 case OMPRTL__kmpc_reduce_nowait: {
1305 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1306 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1307 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1308 // *lck);
1309 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1310 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1311 /*isVarArg=*/false);
1312 llvm::Type *TypeParams[] = {
1313 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1314 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1315 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1316 llvm::FunctionType *FnTy =
1317 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1318 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1319 break;
1320 }
1321 case OMPRTL__kmpc_end_reduce: {
1322 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1323 // kmp_critical_name *lck);
1324 llvm::Type *TypeParams[] = {
1325 getIdentTyPointerTy(), CGM.Int32Ty,
1326 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1327 llvm::FunctionType *FnTy =
1328 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1329 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1330 break;
1331 }
1332 case OMPRTL__kmpc_end_reduce_nowait: {
1333 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1334 // kmp_critical_name *lck);
1335 llvm::Type *TypeParams[] = {
1336 getIdentTyPointerTy(), CGM.Int32Ty,
1337 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1338 llvm::FunctionType *FnTy =
1339 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1340 RTLFn =
1341 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1342 break;
1343 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001344 case OMPRTL__kmpc_omp_task_begin_if0: {
1345 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1346 // *new_task);
1347 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1348 CGM.VoidPtrTy};
1349 llvm::FunctionType *FnTy =
1350 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1351 RTLFn =
1352 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1353 break;
1354 }
1355 case OMPRTL__kmpc_omp_task_complete_if0: {
1356 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1357 // *new_task);
1358 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1359 CGM.VoidPtrTy};
1360 llvm::FunctionType *FnTy =
1361 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1362 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1363 /*Name=*/"__kmpc_omp_task_complete_if0");
1364 break;
1365 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001366 case OMPRTL__kmpc_ordered: {
1367 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1368 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1369 llvm::FunctionType *FnTy =
1370 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1371 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1372 break;
1373 }
1374 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001375 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001376 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1377 llvm::FunctionType *FnTy =
1378 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1379 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1380 break;
1381 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001382 case OMPRTL__kmpc_omp_taskwait: {
1383 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1384 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1385 llvm::FunctionType *FnTy =
1386 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1387 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1388 break;
1389 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001390 case OMPRTL__kmpc_taskgroup: {
1391 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1392 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1393 llvm::FunctionType *FnTy =
1394 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1395 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1396 break;
1397 }
1398 case OMPRTL__kmpc_end_taskgroup: {
1399 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1400 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1401 llvm::FunctionType *FnTy =
1402 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1403 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1404 break;
1405 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001406 case OMPRTL__kmpc_push_proc_bind: {
1407 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1408 // int proc_bind)
1409 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1410 llvm::FunctionType *FnTy =
1411 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1412 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1413 break;
1414 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001415 case OMPRTL__kmpc_omp_task_with_deps: {
1416 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1417 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1418 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1419 llvm::Type *TypeParams[] = {
1420 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1421 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1422 llvm::FunctionType *FnTy =
1423 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1424 RTLFn =
1425 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1426 break;
1427 }
1428 case OMPRTL__kmpc_omp_wait_deps: {
1429 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1430 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1431 // kmp_depend_info_t *noalias_dep_list);
1432 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1433 CGM.Int32Ty, CGM.VoidPtrTy,
1434 CGM.Int32Ty, CGM.VoidPtrTy};
1435 llvm::FunctionType *FnTy =
1436 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1437 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1438 break;
1439 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001440 case OMPRTL__kmpc_cancellationpoint: {
1441 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1442 // global_tid, kmp_int32 cncl_kind)
1443 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1444 llvm::FunctionType *FnTy =
1445 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1446 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1447 break;
1448 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001449 case OMPRTL__kmpc_cancel: {
1450 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1451 // kmp_int32 cncl_kind)
1452 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1453 llvm::FunctionType *FnTy =
1454 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1455 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1456 break;
1457 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001458 case OMPRTL__kmpc_push_num_teams: {
1459 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1460 // kmp_int32 num_teams, kmp_int32 num_threads)
1461 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1462 CGM.Int32Ty};
1463 llvm::FunctionType *FnTy =
1464 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1466 break;
1467 }
1468 case OMPRTL__kmpc_fork_teams: {
1469 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1470 // microtask, ...);
1471 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1472 getKmpc_MicroPointerTy()};
1473 llvm::FunctionType *FnTy =
1474 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1475 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1476 break;
1477 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001478 case OMPRTL__kmpc_taskloop: {
1479 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1480 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1481 // sched, kmp_uint64 grainsize, void *task_dup);
1482 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1483 CGM.IntTy,
1484 CGM.VoidPtrTy,
1485 CGM.IntTy,
1486 CGM.Int64Ty->getPointerTo(),
1487 CGM.Int64Ty->getPointerTo(),
1488 CGM.Int64Ty,
1489 CGM.IntTy,
1490 CGM.IntTy,
1491 CGM.Int64Ty,
1492 CGM.VoidPtrTy};
1493 llvm::FunctionType *FnTy =
1494 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1495 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1496 break;
1497 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001498 case OMPRTL__kmpc_doacross_init: {
1499 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1500 // num_dims, struct kmp_dim *dims);
1501 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1502 CGM.Int32Ty,
1503 CGM.Int32Ty,
1504 CGM.VoidPtrTy};
1505 llvm::FunctionType *FnTy =
1506 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1507 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1508 break;
1509 }
1510 case OMPRTL__kmpc_doacross_fini: {
1511 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1512 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1513 llvm::FunctionType *FnTy =
1514 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1515 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1516 break;
1517 }
1518 case OMPRTL__kmpc_doacross_post: {
1519 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1520 // *vec);
1521 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1522 CGM.Int64Ty->getPointerTo()};
1523 llvm::FunctionType *FnTy =
1524 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1525 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1526 break;
1527 }
1528 case OMPRTL__kmpc_doacross_wait: {
1529 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1530 // *vec);
1531 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1532 CGM.Int64Ty->getPointerTo()};
1533 llvm::FunctionType *FnTy =
1534 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1535 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1536 break;
1537 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001538 case OMPRTL__tgt_target: {
1539 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1540 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1541 // *arg_types);
1542 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1543 CGM.VoidPtrTy,
1544 CGM.Int32Ty,
1545 CGM.VoidPtrPtrTy,
1546 CGM.VoidPtrPtrTy,
1547 CGM.SizeTy->getPointerTo(),
1548 CGM.Int32Ty->getPointerTo()};
1549 llvm::FunctionType *FnTy =
1550 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1551 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1552 break;
1553 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001554 case OMPRTL__tgt_target_teams: {
1555 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1556 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1557 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1558 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1559 CGM.VoidPtrTy,
1560 CGM.Int32Ty,
1561 CGM.VoidPtrPtrTy,
1562 CGM.VoidPtrPtrTy,
1563 CGM.SizeTy->getPointerTo(),
1564 CGM.Int32Ty->getPointerTo(),
1565 CGM.Int32Ty,
1566 CGM.Int32Ty};
1567 llvm::FunctionType *FnTy =
1568 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1569 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1570 break;
1571 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001572 case OMPRTL__tgt_register_lib: {
1573 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1574 QualType ParamTy =
1575 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1576 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1577 llvm::FunctionType *FnTy =
1578 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1579 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1580 break;
1581 }
1582 case OMPRTL__tgt_unregister_lib: {
1583 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1584 QualType ParamTy =
1585 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1586 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1587 llvm::FunctionType *FnTy =
1588 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1589 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1590 break;
1591 }
Samuel Antaodf158d52016-04-27 22:58:19 +00001592 case OMPRTL__tgt_target_data_begin: {
1593 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1594 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1595 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1596 CGM.Int32Ty,
1597 CGM.VoidPtrPtrTy,
1598 CGM.VoidPtrPtrTy,
1599 CGM.SizeTy->getPointerTo(),
1600 CGM.Int32Ty->getPointerTo()};
1601 llvm::FunctionType *FnTy =
1602 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1603 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1604 break;
1605 }
1606 case OMPRTL__tgt_target_data_end: {
1607 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1608 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1609 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1610 CGM.Int32Ty,
1611 CGM.VoidPtrPtrTy,
1612 CGM.VoidPtrPtrTy,
1613 CGM.SizeTy->getPointerTo(),
1614 CGM.Int32Ty->getPointerTo()};
1615 llvm::FunctionType *FnTy =
1616 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1617 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1618 break;
1619 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00001620 case OMPRTL__tgt_target_data_update: {
1621 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1622 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1623 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1624 CGM.Int32Ty,
1625 CGM.VoidPtrPtrTy,
1626 CGM.VoidPtrPtrTy,
1627 CGM.SizeTy->getPointerTo(),
1628 CGM.Int32Ty->getPointerTo()};
1629 llvm::FunctionType *FnTy =
1630 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1631 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1632 break;
1633 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001634 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001635 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001636 return RTLFn;
1637}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001638
Alexander Musman21212e42015-03-13 10:38:23 +00001639llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1640 bool IVSigned) {
1641 assert((IVSize == 32 || IVSize == 64) &&
1642 "IV size is not compatible with the omp runtime");
1643 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1644 : "__kmpc_for_static_init_4u")
1645 : (IVSigned ? "__kmpc_for_static_init_8"
1646 : "__kmpc_for_static_init_8u");
1647 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1648 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1649 llvm::Type *TypeParams[] = {
1650 getIdentTyPointerTy(), // loc
1651 CGM.Int32Ty, // tid
1652 CGM.Int32Ty, // schedtype
1653 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1654 PtrTy, // p_lower
1655 PtrTy, // p_upper
1656 PtrTy, // p_stride
1657 ITy, // incr
1658 ITy // chunk
1659 };
1660 llvm::FunctionType *FnTy =
1661 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1662 return CGM.CreateRuntimeFunction(FnTy, Name);
1663}
1664
Alexander Musman92bdaab2015-03-12 13:37:50 +00001665llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1666 bool IVSigned) {
1667 assert((IVSize == 32 || IVSize == 64) &&
1668 "IV size is not compatible with the omp runtime");
1669 auto Name =
1670 IVSize == 32
1671 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1672 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1673 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1674 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1675 CGM.Int32Ty, // tid
1676 CGM.Int32Ty, // schedtype
1677 ITy, // lower
1678 ITy, // upper
1679 ITy, // stride
1680 ITy // chunk
1681 };
1682 llvm::FunctionType *FnTy =
1683 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1684 return CGM.CreateRuntimeFunction(FnTy, Name);
1685}
1686
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001687llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1688 bool IVSigned) {
1689 assert((IVSize == 32 || IVSize == 64) &&
1690 "IV size is not compatible with the omp runtime");
1691 auto Name =
1692 IVSize == 32
1693 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1694 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1695 llvm::Type *TypeParams[] = {
1696 getIdentTyPointerTy(), // loc
1697 CGM.Int32Ty, // tid
1698 };
1699 llvm::FunctionType *FnTy =
1700 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1701 return CGM.CreateRuntimeFunction(FnTy, Name);
1702}
1703
Alexander Musman92bdaab2015-03-12 13:37:50 +00001704llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1705 bool IVSigned) {
1706 assert((IVSize == 32 || IVSize == 64) &&
1707 "IV size is not compatible with the omp runtime");
1708 auto Name =
1709 IVSize == 32
1710 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1711 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1712 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1713 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1714 llvm::Type *TypeParams[] = {
1715 getIdentTyPointerTy(), // loc
1716 CGM.Int32Ty, // tid
1717 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1718 PtrTy, // p_lower
1719 PtrTy, // p_upper
1720 PtrTy // p_stride
1721 };
1722 llvm::FunctionType *FnTy =
1723 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1724 return CGM.CreateRuntimeFunction(FnTy, Name);
1725}
1726
Alexey Bataev97720002014-11-11 04:05:39 +00001727llvm::Constant *
1728CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001729 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1730 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001731 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001732 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001733 Twine(CGM.getMangledName(VD)) + ".cache.");
1734}
1735
John McCall7f416cc2015-09-08 08:05:57 +00001736Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1737 const VarDecl *VD,
1738 Address VDAddr,
1739 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001740 if (CGM.getLangOpts().OpenMPUseTLS &&
1741 CGM.getContext().getTargetInfo().isTLSSupported())
1742 return VDAddr;
1743
John McCall7f416cc2015-09-08 08:05:57 +00001744 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001745 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001746 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1747 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001748 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1749 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001750 return Address(CGF.EmitRuntimeCall(
1751 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1752 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001753}
1754
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001755void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001756 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001757 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1758 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1759 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001760 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1761 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001762 OMPLoc);
1763 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1764 // to register constructor/destructor for variable.
1765 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001766 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1767 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001768 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001769 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001770 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001771}
1772
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001773llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001774 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001775 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001776 if (CGM.getLangOpts().OpenMPUseTLS &&
1777 CGM.getContext().getTargetInfo().isTLSSupported())
1778 return nullptr;
1779
Alexey Bataev97720002014-11-11 04:05:39 +00001780 VD = VD->getDefinition(CGM.getContext());
1781 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1782 ThreadPrivateWithDefinition.insert(VD);
1783 QualType ASTTy = VD->getType();
1784
1785 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1786 auto Init = VD->getAnyInitializer();
1787 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1788 // Generate function that re-emits the declaration's initializer into the
1789 // threadprivate copy of the variable VD
1790 CodeGenFunction CtorCGF(CGM);
1791 FunctionArgList Args;
1792 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1793 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1794 Args.push_back(&Dst);
1795
John McCallc56a8b32016-03-11 04:30:31 +00001796 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1797 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001798 auto FTy = CGM.getTypes().GetFunctionType(FI);
1799 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001800 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001801 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1802 Args, SourceLocation());
1803 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001804 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001805 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001806 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1807 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1808 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001809 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1810 /*IsInitializer=*/true);
1811 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001812 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001813 CGM.getContext().VoidPtrTy, Dst.getLocation());
1814 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1815 CtorCGF.FinishFunction();
1816 Ctor = Fn;
1817 }
1818 if (VD->getType().isDestructedType() != QualType::DK_none) {
1819 // Generate function that emits destructor call for the threadprivate copy
1820 // of the variable VD
1821 CodeGenFunction DtorCGF(CGM);
1822 FunctionArgList Args;
1823 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1824 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1825 Args.push_back(&Dst);
1826
John McCallc56a8b32016-03-11 04:30:31 +00001827 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1828 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001829 auto FTy = CGM.getTypes().GetFunctionType(FI);
1830 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001831 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001832 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001833 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1834 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001835 // Create a scope with an artificial location for the body of this function.
1836 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001837 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1838 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001839 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1840 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001841 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1842 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1843 DtorCGF.FinishFunction();
1844 Dtor = Fn;
1845 }
1846 // Do not emit init function if it is not required.
1847 if (!Ctor && !Dtor)
1848 return nullptr;
1849
1850 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1851 auto CopyCtorTy =
1852 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1853 /*isVarArg=*/false)->getPointerTo();
1854 // Copying constructor for the threadprivate variable.
1855 // Must be NULL - reserved by runtime, but currently it requires that this
1856 // parameter is always NULL. Otherwise it fires assertion.
1857 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1858 if (Ctor == nullptr) {
1859 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1860 /*isVarArg=*/false)->getPointerTo();
1861 Ctor = llvm::Constant::getNullValue(CtorTy);
1862 }
1863 if (Dtor == nullptr) {
1864 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1865 /*isVarArg=*/false)->getPointerTo();
1866 Dtor = llvm::Constant::getNullValue(DtorTy);
1867 }
1868 if (!CGF) {
1869 auto InitFunctionTy =
1870 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1871 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001872 InitFunctionTy, ".__omp_threadprivate_init_.",
1873 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001874 CodeGenFunction InitCGF(CGM);
1875 FunctionArgList ArgList;
1876 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1877 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1878 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001879 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001880 InitCGF.FinishFunction();
1881 return InitFunction;
1882 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001883 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001884 }
1885 return nullptr;
1886}
1887
Alexey Bataev1d677132015-04-22 13:57:31 +00001888/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1889/// function. Here is the logic:
1890/// if (Cond) {
1891/// ThenGen();
1892/// } else {
1893/// ElseGen();
1894/// }
1895static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1896 const RegionCodeGenTy &ThenGen,
1897 const RegionCodeGenTy &ElseGen) {
1898 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1899
1900 // If the condition constant folds and can be elided, try to avoid emitting
1901 // the condition and the dead arm of the if/else.
1902 bool CondConstant;
1903 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001904 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001905 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001906 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001907 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001908 return;
1909 }
1910
1911 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1912 // emit the conditional branch.
1913 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1914 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1915 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1916 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1917
1918 // Emit the 'then' code.
1919 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001920 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001921 CGF.EmitBranch(ContBlock);
1922 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001923 // There is no need to emit line number for unconditional branch.
1924 (void)ApplyDebugLocation::CreateEmpty(CGF);
1925 CGF.EmitBlock(ElseBlock);
1926 ElseGen(CGF);
1927 // There is no need to emit line number for unconditional branch.
1928 (void)ApplyDebugLocation::CreateEmpty(CGF);
1929 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001930 // Emit the continuation block for code after the if.
1931 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001932}
1933
Alexey Bataev1d677132015-04-22 13:57:31 +00001934void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1935 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001936 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001937 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001938 if (!CGF.HaveInsertPoint())
1939 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001940 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001941 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1942 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001943 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001944 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001945 llvm::Value *Args[] = {
1946 RTLoc,
1947 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001948 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001949 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1950 RealArgs.append(std::begin(Args), std::end(Args));
1951 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1952
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001953 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001954 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1955 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001956 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1957 PrePostActionTy &) {
1958 auto &RT = CGF.CGM.getOpenMPRuntime();
1959 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001960 // Build calls:
1961 // __kmpc_serialized_parallel(&Loc, GTid);
1962 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001963 CGF.EmitRuntimeCall(
1964 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001965
Alexey Bataev1d677132015-04-22 13:57:31 +00001966 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001967 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001968 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001969 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1970 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001971 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001972 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1973 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1974 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1975 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001976 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001977
Alexey Bataev1d677132015-04-22 13:57:31 +00001978 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001979 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001980 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001981 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1982 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00001983 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001984 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00001985 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001986 else {
1987 RegionCodeGenTy ThenRCG(ThenGen);
1988 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00001989 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001990}
1991
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001992// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001993// thread-ID variable (it is passed in a first argument of the outlined function
1994// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1995// regular serial code region, get thread ID by calling kmp_int32
1996// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1997// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001998Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1999 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002000 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002001 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002002 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002003 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002004
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002005 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002006 auto Int32Ty =
2007 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2008 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2009 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002010 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002011
2012 return ThreadIDTemp;
2013}
2014
Alexey Bataev97720002014-11-11 04:05:39 +00002015llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002016CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002017 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002018 SmallString<256> Buffer;
2019 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002020 Out << Name;
2021 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002022 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2023 if (Elem.second) {
2024 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002025 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002026 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002027 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002028
David Blaikie13156b62014-11-19 03:06:06 +00002029 return Elem.second = new llvm::GlobalVariable(
2030 CGM.getModule(), Ty, /*IsConstant*/ false,
2031 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2032 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002033}
2034
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002035llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002036 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002037 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002038}
2039
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002040namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002041/// Common pre(post)-action for different OpenMP constructs.
2042class CommonActionTy final : public PrePostActionTy {
2043 llvm::Value *EnterCallee;
2044 ArrayRef<llvm::Value *> EnterArgs;
2045 llvm::Value *ExitCallee;
2046 ArrayRef<llvm::Value *> ExitArgs;
2047 bool Conditional;
2048 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002049
2050public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002051 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2052 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2053 bool Conditional = false)
2054 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2055 ExitArgs(ExitArgs), Conditional(Conditional) {}
2056 void Enter(CodeGenFunction &CGF) override {
2057 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2058 if (Conditional) {
2059 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2060 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2061 ContBlock = CGF.createBasicBlock("omp_if.end");
2062 // Generate the branch (If-stmt)
2063 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2064 CGF.EmitBlock(ThenBlock);
2065 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002066 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002067 void Done(CodeGenFunction &CGF) {
2068 // Emit the rest of blocks/branches
2069 CGF.EmitBranch(ContBlock);
2070 CGF.EmitBlock(ContBlock, true);
2071 }
2072 void Exit(CodeGenFunction &CGF) override {
2073 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002074 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002075};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002076} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002077
2078void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2079 StringRef CriticalName,
2080 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002081 SourceLocation Loc, const Expr *Hint) {
2082 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002083 // CriticalOpGen();
2084 // __kmpc_end_critical(ident_t *, gtid, Lock);
2085 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002086 if (!CGF.HaveInsertPoint())
2087 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002088 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2089 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002090 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2091 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002092 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002093 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2094 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2095 }
2096 CommonActionTy Action(
2097 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2098 : OMPRTL__kmpc_critical),
2099 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2100 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002101 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002102}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002103
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002104void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002105 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002106 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002107 if (!CGF.HaveInsertPoint())
2108 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002109 // if(__kmpc_master(ident_t *, gtid)) {
2110 // MasterOpGen();
2111 // __kmpc_end_master(ident_t *, gtid);
2112 // }
2113 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002114 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002115 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2116 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2117 /*Conditional=*/true);
2118 MasterOpGen.setAction(Action);
2119 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2120 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002121}
2122
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002123void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2124 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002125 if (!CGF.HaveInsertPoint())
2126 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002127 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2128 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002129 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002130 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002131 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002132 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2133 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002134}
2135
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002136void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2137 const RegionCodeGenTy &TaskgroupOpGen,
2138 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002139 if (!CGF.HaveInsertPoint())
2140 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002141 // __kmpc_taskgroup(ident_t *, gtid);
2142 // TaskgroupOpGen();
2143 // __kmpc_end_taskgroup(ident_t *, gtid);
2144 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002145 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2146 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2147 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2148 Args);
2149 TaskgroupOpGen.setAction(Action);
2150 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002151}
2152
John McCall7f416cc2015-09-08 08:05:57 +00002153/// Given an array of pointers to variables, project the address of a
2154/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002155static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2156 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002157 // Pull out the pointer to the variable.
2158 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002159 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002160 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2161
2162 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002163 Addr = CGF.Builder.CreateElementBitCast(
2164 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002165 return Addr;
2166}
2167
Alexey Bataeva63048e2015-03-23 06:18:07 +00002168static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002169 CodeGenModule &CGM, llvm::Type *ArgsType,
2170 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2171 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002172 auto &C = CGM.getContext();
2173 // void copy_func(void *LHSArg, void *RHSArg);
2174 FunctionArgList Args;
2175 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2176 C.VoidPtrTy);
2177 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2178 C.VoidPtrTy);
2179 Args.push_back(&LHSArg);
2180 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002181 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002182 auto *Fn = llvm::Function::Create(
2183 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2184 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002185 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002186 CodeGenFunction CGF(CGM);
2187 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002188 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002189 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002190 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2191 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2192 ArgsType), CGF.getPointerAlign());
2193 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2194 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2195 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002196 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2197 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2198 // ...
2199 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002200 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002201 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2202 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2203
2204 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2205 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2206
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002207 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2208 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002209 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002210 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002211 CGF.FinishFunction();
2212 return Fn;
2213}
2214
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002215void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002216 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002217 SourceLocation Loc,
2218 ArrayRef<const Expr *> CopyprivateVars,
2219 ArrayRef<const Expr *> SrcExprs,
2220 ArrayRef<const Expr *> DstExprs,
2221 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002222 if (!CGF.HaveInsertPoint())
2223 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002224 assert(CopyprivateVars.size() == SrcExprs.size() &&
2225 CopyprivateVars.size() == DstExprs.size() &&
2226 CopyprivateVars.size() == AssignmentOps.size());
2227 auto &C = CGM.getContext();
2228 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002229 // if(__kmpc_single(ident_t *, gtid)) {
2230 // SingleOpGen();
2231 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002232 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002233 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002234 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2235 // <copy_func>, did_it);
2236
John McCall7f416cc2015-09-08 08:05:57 +00002237 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002238 if (!CopyprivateVars.empty()) {
2239 // int32 did_it = 0;
2240 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2241 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002242 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002243 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002244 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002245 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002246 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2247 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2248 /*Conditional=*/true);
2249 SingleOpGen.setAction(Action);
2250 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2251 if (DidIt.isValid()) {
2252 // did_it = 1;
2253 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2254 }
2255 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002256 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2257 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002258 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002259 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2260 auto CopyprivateArrayTy =
2261 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2262 /*IndexTypeQuals=*/0);
2263 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002264 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002265 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2266 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002267 Address Elem = CGF.Builder.CreateConstArrayGEP(
2268 CopyprivateList, I, CGF.getPointerSize());
2269 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002270 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002271 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2272 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002273 }
2274 // Build function that copies private values from single region to all other
2275 // threads in the corresponding parallel region.
2276 auto *CpyFn = emitCopyprivateCopyFunction(
2277 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002278 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002279 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002280 Address CL =
2281 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2282 CGF.VoidPtrTy);
2283 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002284 llvm::Value *Args[] = {
2285 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2286 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002287 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002288 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002289 CpyFn, // void (*) (void *, void *) <copy_func>
2290 DidItVal // i32 did_it
2291 };
2292 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2293 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002294}
2295
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002296void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2297 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002298 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002299 if (!CGF.HaveInsertPoint())
2300 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002301 // __kmpc_ordered(ident_t *, gtid);
2302 // OrderedOpGen();
2303 // __kmpc_end_ordered(ident_t *, gtid);
2304 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002305 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002306 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002307 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2308 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2309 Args);
2310 OrderedOpGen.setAction(Action);
2311 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2312 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002313 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002314 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002315}
2316
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002317void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002318 OpenMPDirectiveKind Kind, bool EmitChecks,
2319 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002320 if (!CGF.HaveInsertPoint())
2321 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002322 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002323 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002324 unsigned Flags;
2325 if (Kind == OMPD_for)
2326 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2327 else if (Kind == OMPD_sections)
2328 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2329 else if (Kind == OMPD_single)
2330 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2331 else if (Kind == OMPD_barrier)
2332 Flags = OMP_IDENT_BARRIER_EXPL;
2333 else
2334 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002335 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2336 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002337 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2338 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002339 if (auto *OMPRegionInfo =
2340 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002341 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002342 auto *Result = CGF.EmitRuntimeCall(
2343 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002344 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002345 // if (__kmpc_cancel_barrier()) {
2346 // exit from construct;
2347 // }
2348 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2349 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2350 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2351 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2352 CGF.EmitBlock(ExitBB);
2353 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002354 auto CancelDestination =
2355 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002356 CGF.EmitBranchThroughCleanup(CancelDestination);
2357 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2358 }
2359 return;
2360 }
2361 }
2362 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002363}
2364
Alexander Musmanc6388682014-12-15 07:07:06 +00002365/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2366static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002367 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002368 switch (ScheduleKind) {
2369 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002370 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2371 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002372 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002373 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002374 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002375 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002376 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002377 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2378 case OMPC_SCHEDULE_auto:
2379 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002380 case OMPC_SCHEDULE_unknown:
2381 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002382 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002383 }
2384 llvm_unreachable("Unexpected runtime schedule");
2385}
2386
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002387/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2388static OpenMPSchedType
2389getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2390 // only static is allowed for dist_schedule
2391 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2392}
2393
Alexander Musmanc6388682014-12-15 07:07:06 +00002394bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2395 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002396 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002397 return Schedule == OMP_sch_static;
2398}
2399
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002400bool CGOpenMPRuntime::isStaticNonchunked(
2401 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2402 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2403 return Schedule == OMP_dist_sch_static;
2404}
2405
2406
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002407bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002408 auto Schedule =
2409 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002410 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2411 return Schedule != OMP_sch_static;
2412}
2413
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002414static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2415 OpenMPScheduleClauseModifier M1,
2416 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002417 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002418 switch (M1) {
2419 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002420 Modifier = OMP_sch_modifier_monotonic;
2421 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002422 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002423 Modifier = OMP_sch_modifier_nonmonotonic;
2424 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002425 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002426 if (Schedule == OMP_sch_static_chunked)
2427 Schedule = OMP_sch_static_balanced_chunked;
2428 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002429 case OMPC_SCHEDULE_MODIFIER_last:
2430 case OMPC_SCHEDULE_MODIFIER_unknown:
2431 break;
2432 }
2433 switch (M2) {
2434 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002435 Modifier = OMP_sch_modifier_monotonic;
2436 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002437 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002438 Modifier = OMP_sch_modifier_nonmonotonic;
2439 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002440 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002441 if (Schedule == OMP_sch_static_chunked)
2442 Schedule = OMP_sch_static_balanced_chunked;
2443 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002444 case OMPC_SCHEDULE_MODIFIER_last:
2445 case OMPC_SCHEDULE_MODIFIER_unknown:
2446 break;
2447 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002448 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002449}
2450
John McCall7f416cc2015-09-08 08:05:57 +00002451void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2452 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002453 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002454 unsigned IVSize, bool IVSigned,
2455 bool Ordered, llvm::Value *UB,
2456 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002457 if (!CGF.HaveInsertPoint())
2458 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002459 OpenMPSchedType Schedule =
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002460 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002461 assert(Ordered ||
2462 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002463 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2464 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002465 // Call __kmpc_dispatch_init(
2466 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2467 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2468 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002469
John McCall7f416cc2015-09-08 08:05:57 +00002470 // If the Chunk was not specified in the clause - use default value 1.
2471 if (Chunk == nullptr)
2472 Chunk = CGF.Builder.getIntN(IVSize, 1);
2473 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002474 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2475 CGF.Builder.getInt32(addMonoNonMonoModifier(
2476 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2477 CGF.Builder.getIntN(IVSize, 0), // Lower
2478 UB, // Upper
2479 CGF.Builder.getIntN(IVSize, 1), // Stride
2480 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002481 };
2482 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2483}
2484
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002485static void emitForStaticInitCall(
2486 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2487 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2488 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2489 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2490 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002491 if (!CGF.HaveInsertPoint())
2492 return;
2493
2494 assert(!Ordered);
2495 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002496 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002497 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2498 Schedule == OMP_dist_sch_static ||
2499 Schedule == OMP_dist_sch_static_chunked);
2500
2501 // Call __kmpc_for_static_init(
2502 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2503 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2504 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2505 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2506 if (Chunk == nullptr) {
2507 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2508 Schedule == OMP_dist_sch_static) &&
2509 "expected static non-chunked schedule");
2510 // If the Chunk was not specified in the clause - use default value 1.
2511 Chunk = CGF.Builder.getIntN(IVSize, 1);
2512 } else {
2513 assert((Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002514 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002515 Schedule == OMP_ord_static_chunked ||
2516 Schedule == OMP_dist_sch_static_chunked) &&
2517 "expected static chunked schedule");
2518 }
2519 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002520 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2521 Schedule, M1, M2)), // Schedule type
2522 IL.getPointer(), // &isLastIter
2523 LB.getPointer(), // &LB
2524 UB.getPointer(), // &UB
2525 ST.getPointer(), // &Stride
2526 CGF.Builder.getIntN(IVSize, 1), // Incr
2527 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002528 };
2529 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2530}
2531
John McCall7f416cc2015-09-08 08:05:57 +00002532void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2533 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002534 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002535 unsigned IVSize, bool IVSigned,
2536 bool Ordered, Address IL, Address LB,
2537 Address UB, Address ST,
2538 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002539 OpenMPSchedType ScheduleNum =
2540 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002541 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2542 auto *ThreadId = getThreadID(CGF, Loc);
2543 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002544 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2545 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2546 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002547}
John McCall7f416cc2015-09-08 08:05:57 +00002548
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002549void CGOpenMPRuntime::emitDistributeStaticInit(
2550 CodeGenFunction &CGF, SourceLocation Loc,
2551 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2552 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002553 llvm::Value *Chunk) {
2554 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2555 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2556 auto *ThreadId = getThreadID(CGF, Loc);
2557 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002558 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2559 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2560 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2561 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002562}
2563
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002564void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2565 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002566 if (!CGF.HaveInsertPoint())
2567 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002568 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002569 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002570 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2571 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002572}
2573
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002574void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2575 SourceLocation Loc,
2576 unsigned IVSize,
2577 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002578 if (!CGF.HaveInsertPoint())
2579 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002580 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002581 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002582 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2583}
2584
Alexander Musman92bdaab2015-03-12 13:37:50 +00002585llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2586 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002587 bool IVSigned, Address IL,
2588 Address LB, Address UB,
2589 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002590 // Call __kmpc_dispatch_next(
2591 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2592 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2593 // kmp_int[32|64] *p_stride);
2594 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002595 emitUpdateLocation(CGF, Loc),
2596 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002597 IL.getPointer(), // &isLastIter
2598 LB.getPointer(), // &Lower
2599 UB.getPointer(), // &Upper
2600 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002601 };
2602 llvm::Value *Call =
2603 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2604 return CGF.EmitScalarConversion(
2605 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002606 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002607}
2608
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002609void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2610 llvm::Value *NumThreads,
2611 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002612 if (!CGF.HaveInsertPoint())
2613 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002614 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2615 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002616 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002617 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002618 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2619 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002620}
2621
Alexey Bataev7f210c62015-06-18 13:40:03 +00002622void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2623 OpenMPProcBindClauseKind ProcBind,
2624 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002625 if (!CGF.HaveInsertPoint())
2626 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002627 // Constants for proc bind value accepted by the runtime.
2628 enum ProcBindTy {
2629 ProcBindFalse = 0,
2630 ProcBindTrue,
2631 ProcBindMaster,
2632 ProcBindClose,
2633 ProcBindSpread,
2634 ProcBindIntel,
2635 ProcBindDefault
2636 } RuntimeProcBind;
2637 switch (ProcBind) {
2638 case OMPC_PROC_BIND_master:
2639 RuntimeProcBind = ProcBindMaster;
2640 break;
2641 case OMPC_PROC_BIND_close:
2642 RuntimeProcBind = ProcBindClose;
2643 break;
2644 case OMPC_PROC_BIND_spread:
2645 RuntimeProcBind = ProcBindSpread;
2646 break;
2647 case OMPC_PROC_BIND_unknown:
2648 llvm_unreachable("Unsupported proc_bind value.");
2649 }
2650 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2651 llvm::Value *Args[] = {
2652 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2653 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2654 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2655}
2656
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002657void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2658 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002659 if (!CGF.HaveInsertPoint())
2660 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002661 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002662 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2663 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002664}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002665
Alexey Bataev62b63b12015-03-10 07:28:44 +00002666namespace {
2667/// \brief Indexes of fields for type kmp_task_t.
2668enum KmpTaskTFields {
2669 /// \brief List of shared variables.
2670 KmpTaskTShareds,
2671 /// \brief Task routine.
2672 KmpTaskTRoutine,
2673 /// \brief Partition id for the untied tasks.
2674 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00002675 /// Function with call of destructors for private variables.
2676 Data1,
2677 /// Task priority.
2678 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00002679 /// (Taskloops only) Lower bound.
2680 KmpTaskTLowerBound,
2681 /// (Taskloops only) Upper bound.
2682 KmpTaskTUpperBound,
2683 /// (Taskloops only) Stride.
2684 KmpTaskTStride,
2685 /// (Taskloops only) Is last iteration flag.
2686 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002687};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002688} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002689
Samuel Antaoee8fb302016-01-06 13:42:12 +00002690bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2691 // FIXME: Add other entries type when they become supported.
2692 return OffloadEntriesTargetRegion.empty();
2693}
2694
2695/// \brief Initialize target region entry.
2696void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2697 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2698 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002699 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002700 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2701 "only required for the device "
2702 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002703 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00002704 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
2705 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002706 ++OffloadingEntriesNum;
2707}
2708
2709void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2710 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2711 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002712 llvm::Constant *Addr, llvm::Constant *ID,
2713 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002714 // If we are emitting code for a target, the entry is already initialized,
2715 // only has to be registered.
2716 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002717 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002718 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002719 auto &Entry =
2720 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002721 assert(Entry.isValid() && "Entry not initialized!");
2722 Entry.setAddress(Addr);
2723 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002724 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002725 return;
2726 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00002727 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00002728 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002729 }
2730}
2731
2732bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002733 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2734 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002735 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2736 if (PerDevice == OffloadEntriesTargetRegion.end())
2737 return false;
2738 auto PerFile = PerDevice->second.find(FileID);
2739 if (PerFile == PerDevice->second.end())
2740 return false;
2741 auto PerParentName = PerFile->second.find(ParentName);
2742 if (PerParentName == PerFile->second.end())
2743 return false;
2744 auto PerLine = PerParentName->second.find(LineNum);
2745 if (PerLine == PerParentName->second.end())
2746 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002747 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002748 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002749 return false;
2750 return true;
2751}
2752
2753void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2754 const OffloadTargetRegionEntryInfoActTy &Action) {
2755 // Scan all target region entries and perform the provided action.
2756 for (auto &D : OffloadEntriesTargetRegion)
2757 for (auto &F : D.second)
2758 for (auto &P : F.second)
2759 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002760 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002761}
2762
2763/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2764/// \a Codegen. This is used to emit the two functions that register and
2765/// unregister the descriptor of the current compilation unit.
2766static llvm::Function *
2767createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2768 const RegionCodeGenTy &Codegen) {
2769 auto &C = CGM.getContext();
2770 FunctionArgList Args;
2771 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2772 /*Id=*/nullptr, C.VoidPtrTy);
2773 Args.push_back(&DummyPtr);
2774
2775 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00002776 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002777 auto FTy = CGM.getTypes().GetFunctionType(FI);
2778 auto *Fn =
2779 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2780 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2781 Codegen(CGF);
2782 CGF.FinishFunction();
2783 return Fn;
2784}
2785
2786llvm::Function *
2787CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2788
2789 // If we don't have entries or if we are emitting code for the device, we
2790 // don't need to do anything.
2791 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2792 return nullptr;
2793
2794 auto &M = CGM.getModule();
2795 auto &C = CGM.getContext();
2796
2797 // Get list of devices we care about
2798 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2799
2800 // We should be creating an offloading descriptor only if there are devices
2801 // specified.
2802 assert(!Devices.empty() && "No OpenMP offloading devices??");
2803
2804 // Create the external variables that will point to the begin and end of the
2805 // host entries section. These will be defined by the linker.
2806 auto *OffloadEntryTy =
2807 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2808 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2809 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002810 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002811 ".omp_offloading.entries_begin");
2812 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2813 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002814 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002815 ".omp_offloading.entries_end");
2816
2817 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00002818 auto *DeviceImageTy = cast<llvm::StructType>(
2819 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002820 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002821 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002822
2823 for (unsigned i = 0; i < Devices.size(); ++i) {
2824 StringRef T = Devices[i].getTriple();
2825 auto *ImgBegin = new llvm::GlobalVariable(
2826 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002827 /*Initializer=*/nullptr,
2828 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002829 auto *ImgEnd = new llvm::GlobalVariable(
2830 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002831 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002832
John McCall6c9f1fdb2016-11-19 08:17:24 +00002833 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2834 Dev.add(ImgBegin);
2835 Dev.add(ImgEnd);
2836 Dev.add(HostEntriesBegin);
2837 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00002838 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002839 }
2840
2841 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002842 llvm::GlobalVariable *DeviceImages =
2843 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2844 CGM.getPointerAlign(),
2845 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002846 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002847
2848 // This is a Zero array to be used in the creation of the constant expressions
2849 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2850 llvm::Constant::getNullValue(CGM.Int32Ty)};
2851
2852 // Create the target region descriptor.
2853 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2854 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002855 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002856 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2857 DescInit.addInt(CGM.Int32Ty, Devices.size());
2858 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2859 DeviceImages,
2860 Index));
2861 DescInit.add(HostEntriesBegin);
2862 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002863
John McCall6c9f1fdb2016-11-19 08:17:24 +00002864 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2865 CGM.getPointerAlign(),
2866 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002867
2868 // Emit code to register or unregister the descriptor at execution
2869 // startup or closing, respectively.
2870
2871 // Create a variable to drive the registration and unregistration of the
2872 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2873 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2874 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2875 IdentInfo, C.CharTy);
2876
2877 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002878 CGM, ".omp_offloading.descriptor_unreg",
2879 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002880 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2881 Desc);
2882 });
2883 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002884 CGM, ".omp_offloading.descriptor_reg",
2885 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002886 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2887 Desc);
2888 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2889 });
2890 return RegFn;
2891}
2892
Samuel Antao2de62b02016-02-13 23:35:10 +00002893void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002894 llvm::Constant *Addr, uint64_t Size,
2895 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002896 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002897 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2898 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2899 llvm::LLVMContext &C = CGM.getModule().getContext();
2900 llvm::Module &M = CGM.getModule();
2901
2902 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002903 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002904
2905 // Create constant string with the name.
2906 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2907
2908 llvm::GlobalVariable *Str =
2909 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2910 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2911 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002912 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002913 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2914
John McCall6c9f1fdb2016-11-19 08:17:24 +00002915 // We can't have any padding between symbols, so we need to have 1-byte
2916 // alignment.
2917 auto Align = CharUnits::fromQuantity(1);
2918
Samuel Antaoee8fb302016-01-06 13:42:12 +00002919 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00002920 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002921 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2922 EntryInit.add(AddrPtr);
2923 EntryInit.add(StrPtr);
2924 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002925 EntryInit.addInt(CGM.Int32Ty, Flags);
2926 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002927 llvm::GlobalVariable *Entry =
2928 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2929 Align,
2930 /*constant*/ true,
2931 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002932
2933 // The entry has to be created in the section the linker expects it to be.
2934 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00002935}
2936
2937void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2938 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00002939 // can easily figure out what to emit. The produced metadata looks like
2940 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00002941 //
2942 // !omp_offload.info = !{!1, ...}
2943 //
2944 // Right now we only generate metadata for function that contain target
2945 // regions.
2946
2947 // If we do not have entries, we dont need to do anything.
2948 if (OffloadEntriesInfoManager.empty())
2949 return;
2950
2951 llvm::Module &M = CGM.getModule();
2952 llvm::LLVMContext &C = M.getContext();
2953 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2954 OrderedEntries(OffloadEntriesInfoManager.size());
2955
2956 // Create the offloading info metadata node.
2957 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2958
2959 // Auxiliar methods to create metadata values and strings.
2960 auto getMDInt = [&](unsigned v) {
2961 return llvm::ConstantAsMetadata::get(
2962 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2963 };
2964
2965 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2966
2967 // Create function that emits metadata for each target region entry;
2968 auto &&TargetRegionMetadataEmitter = [&](
2969 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002970 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2971 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2972 // Generate metadata for target regions. Each entry of this metadata
2973 // contains:
2974 // - Entry 0 -> Kind of this type of metadata (0).
2975 // - Entry 1 -> Device ID of the file where the entry was identified.
2976 // - Entry 2 -> File ID of the file where the entry was identified.
2977 // - Entry 3 -> Mangled name of the function where the entry was identified.
2978 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002979 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002980 // The first element of the metadata node is the kind.
2981 Ops.push_back(getMDInt(E.getKind()));
2982 Ops.push_back(getMDInt(DeviceID));
2983 Ops.push_back(getMDInt(FileID));
2984 Ops.push_back(getMDString(ParentName));
2985 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002986 Ops.push_back(getMDInt(E.getOrder()));
2987
2988 // Save this entry in the right position of the ordered entries array.
2989 OrderedEntries[E.getOrder()] = &E;
2990
2991 // Add metadata to the named metadata node.
2992 MD->addOperand(llvm::MDNode::get(C, Ops));
2993 };
2994
2995 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2996 TargetRegionMetadataEmitter);
2997
2998 for (auto *E : OrderedEntries) {
2999 assert(E && "All ordered entries must exist!");
3000 if (auto *CE =
3001 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3002 E)) {
3003 assert(CE->getID() && CE->getAddress() &&
3004 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003005 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003006 } else
3007 llvm_unreachable("Unsupported entry kind.");
3008 }
3009}
3010
3011/// \brief Loads all the offload entries information from the host IR
3012/// metadata.
3013void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3014 // If we are in target mode, load the metadata from the host IR. This code has
3015 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3016
3017 if (!CGM.getLangOpts().OpenMPIsDevice)
3018 return;
3019
3020 if (CGM.getLangOpts().OMPHostIRFile.empty())
3021 return;
3022
3023 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3024 if (Buf.getError())
3025 return;
3026
3027 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003028 auto ME = expectedToErrorOrAndEmitErrors(
3029 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003030
3031 if (ME.getError())
3032 return;
3033
3034 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3035 if (!MD)
3036 return;
3037
3038 for (auto I : MD->operands()) {
3039 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3040
3041 auto getMDInt = [&](unsigned Idx) {
3042 llvm::ConstantAsMetadata *V =
3043 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3044 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3045 };
3046
3047 auto getMDString = [&](unsigned Idx) {
3048 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3049 return V->getString();
3050 };
3051
3052 switch (getMDInt(0)) {
3053 default:
3054 llvm_unreachable("Unexpected metadata!");
3055 break;
3056 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3057 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3058 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3059 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3060 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003061 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003062 break;
3063 }
3064 }
3065}
3066
Alexey Bataev62b63b12015-03-10 07:28:44 +00003067void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3068 if (!KmpRoutineEntryPtrTy) {
3069 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3070 auto &C = CGM.getContext();
3071 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3072 FunctionProtoType::ExtProtoInfo EPI;
3073 KmpRoutineEntryPtrQTy = C.getPointerType(
3074 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3075 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3076 }
3077}
3078
Alexey Bataevc71a4092015-09-11 10:29:41 +00003079static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3080 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003081 auto *Field = FieldDecl::Create(
3082 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3083 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3084 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3085 Field->setAccess(AS_public);
3086 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003087 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003088}
3089
Samuel Antaoee8fb302016-01-06 13:42:12 +00003090QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3091
3092 // Make sure the type of the entry is already created. This is the type we
3093 // have to create:
3094 // struct __tgt_offload_entry{
3095 // void *addr; // Pointer to the offload entry info.
3096 // // (function or global)
3097 // char *name; // Name of the function or global.
3098 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003099 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3100 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003101 // };
3102 if (TgtOffloadEntryQTy.isNull()) {
3103 ASTContext &C = CGM.getContext();
3104 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3105 RD->startDefinition();
3106 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3107 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3108 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003109 addFieldToRecordDecl(
3110 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3111 addFieldToRecordDecl(
3112 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003113 RD->completeDefinition();
3114 TgtOffloadEntryQTy = C.getRecordType(RD);
3115 }
3116 return TgtOffloadEntryQTy;
3117}
3118
3119QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3120 // These are the types we need to build:
3121 // struct __tgt_device_image{
3122 // void *ImageStart; // Pointer to the target code start.
3123 // void *ImageEnd; // Pointer to the target code end.
3124 // // We also add the host entries to the device image, as it may be useful
3125 // // for the target runtime to have access to that information.
3126 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3127 // // the entries.
3128 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3129 // // entries (non inclusive).
3130 // };
3131 if (TgtDeviceImageQTy.isNull()) {
3132 ASTContext &C = CGM.getContext();
3133 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3134 RD->startDefinition();
3135 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3136 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3137 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3138 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3139 RD->completeDefinition();
3140 TgtDeviceImageQTy = C.getRecordType(RD);
3141 }
3142 return TgtDeviceImageQTy;
3143}
3144
3145QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3146 // struct __tgt_bin_desc{
3147 // int32_t NumDevices; // Number of devices supported.
3148 // __tgt_device_image *DeviceImages; // Arrays of device images
3149 // // (one per device).
3150 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3151 // // entries.
3152 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3153 // // entries (non inclusive).
3154 // };
3155 if (TgtBinaryDescriptorQTy.isNull()) {
3156 ASTContext &C = CGM.getContext();
3157 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3158 RD->startDefinition();
3159 addFieldToRecordDecl(
3160 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3161 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3162 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3163 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3164 RD->completeDefinition();
3165 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3166 }
3167 return TgtBinaryDescriptorQTy;
3168}
3169
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003170namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003171struct PrivateHelpersTy {
3172 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3173 const VarDecl *PrivateElemInit)
3174 : Original(Original), PrivateCopy(PrivateCopy),
3175 PrivateElemInit(PrivateElemInit) {}
3176 const VarDecl *Original;
3177 const VarDecl *PrivateCopy;
3178 const VarDecl *PrivateElemInit;
3179};
3180typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003181} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003182
Alexey Bataev9e034042015-05-05 04:05:12 +00003183static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003184createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003185 if (!Privates.empty()) {
3186 auto &C = CGM.getContext();
3187 // Build struct .kmp_privates_t. {
3188 // /* private vars */
3189 // };
3190 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3191 RD->startDefinition();
3192 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003193 auto *VD = Pair.second.Original;
3194 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003195 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003196 auto *FD = addFieldToRecordDecl(C, RD, Type);
3197 if (VD->hasAttrs()) {
3198 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3199 E(VD->getAttrs().end());
3200 I != E; ++I)
3201 FD->addAttr(*I);
3202 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003203 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003204 RD->completeDefinition();
3205 return RD;
3206 }
3207 return nullptr;
3208}
3209
Alexey Bataev9e034042015-05-05 04:05:12 +00003210static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003211createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3212 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003213 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003214 auto &C = CGM.getContext();
3215 // Build struct kmp_task_t {
3216 // void * shareds;
3217 // kmp_routine_entry_t routine;
3218 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003219 // kmp_cmplrdata_t data1;
3220 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003221 // For taskloops additional fields:
3222 // kmp_uint64 lb;
3223 // kmp_uint64 ub;
3224 // kmp_int64 st;
3225 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003226 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003227 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3228 UD->startDefinition();
3229 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3230 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3231 UD->completeDefinition();
3232 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003233 auto *RD = C.buildImplicitRecord("kmp_task_t");
3234 RD->startDefinition();
3235 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3236 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3237 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003238 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3239 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003240 if (isOpenMPTaskLoopDirective(Kind)) {
3241 QualType KmpUInt64Ty =
3242 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3243 QualType KmpInt64Ty =
3244 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3245 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3246 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3247 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3248 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3249 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003250 RD->completeDefinition();
3251 return RD;
3252}
3253
3254static RecordDecl *
3255createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003256 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003257 auto &C = CGM.getContext();
3258 // Build struct kmp_task_t_with_privates {
3259 // kmp_task_t task_data;
3260 // .kmp_privates_t. privates;
3261 // };
3262 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3263 RD->startDefinition();
3264 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003265 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3266 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3267 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003268 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003269 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003270}
3271
3272/// \brief Emit a proxy function which accepts kmp_task_t as the second
3273/// argument.
3274/// \code
3275/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003276/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003277/// For taskloops:
3278/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003279/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003280/// return 0;
3281/// }
3282/// \endcode
3283static llvm::Value *
3284emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003285 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3286 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003287 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003288 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3289 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003290 auto &C = CGM.getContext();
3291 FunctionArgList Args;
3292 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3293 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003294 /*Id=*/nullptr,
3295 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003296 Args.push_back(&GtidArg);
3297 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003298 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003299 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003300 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3301 auto *TaskEntry =
3302 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3303 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003304 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003305 CodeGenFunction CGF(CGM);
3306 CGF.disableDebugInfo();
3307 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3308
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003309 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003310 // tt,
3311 // For taskloops:
3312 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3313 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003314 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003315 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003316 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3317 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3318 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003319 auto *KmpTaskTWithPrivatesQTyRD =
3320 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003321 LValue Base =
3322 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003323 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3324 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3325 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003326 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003327
3328 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3329 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003330 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003331 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003332 CGF.ConvertTypeForMem(SharedsPtrTy));
3333
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003334 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3335 llvm::Value *PrivatesParam;
3336 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3337 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3338 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003339 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003340 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003341 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003342
Alexey Bataev7292c292016-04-25 12:22:29 +00003343 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3344 TaskPrivatesMap,
3345 CGF.Builder
3346 .CreatePointerBitCastOrAddrSpaceCast(
3347 TDBase.getAddress(), CGF.VoidPtrTy)
3348 .getPointer()};
3349 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3350 std::end(CommonArgs));
3351 if (isOpenMPTaskLoopDirective(Kind)) {
3352 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3353 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3354 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3355 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3356 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3357 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3358 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3359 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3360 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3361 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3362 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3363 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3364 CallArgs.push_back(LBParam);
3365 CallArgs.push_back(UBParam);
3366 CallArgs.push_back(StParam);
3367 CallArgs.push_back(LIParam);
3368 }
3369 CallArgs.push_back(SharedsParam);
3370
Alexey Bataev62b63b12015-03-10 07:28:44 +00003371 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3372 CGF.EmitStoreThroughLValue(
3373 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003374 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003375 CGF.FinishFunction();
3376 return TaskEntry;
3377}
3378
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003379static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3380 SourceLocation Loc,
3381 QualType KmpInt32Ty,
3382 QualType KmpTaskTWithPrivatesPtrQTy,
3383 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003384 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003385 FunctionArgList Args;
3386 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3387 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003388 /*Id=*/nullptr,
3389 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003390 Args.push_back(&GtidArg);
3391 Args.push_back(&TaskTypeArg);
3392 FunctionType::ExtInfo Info;
3393 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003394 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003395 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3396 auto *DestructorFn =
3397 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3398 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003399 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3400 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003401 CodeGenFunction CGF(CGM);
3402 CGF.disableDebugInfo();
3403 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3404 Args);
3405
Alexey Bataev31300ed2016-02-04 11:27:03 +00003406 LValue Base = CGF.EmitLoadOfPointerLValue(
3407 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3408 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003409 auto *KmpTaskTWithPrivatesQTyRD =
3410 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3411 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003412 Base = CGF.EmitLValueForField(Base, *FI);
3413 for (auto *Field :
3414 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3415 if (auto DtorKind = Field->getType().isDestructedType()) {
3416 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3417 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3418 }
3419 }
3420 CGF.FinishFunction();
3421 return DestructorFn;
3422}
3423
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003424/// \brief Emit a privates mapping function for correct handling of private and
3425/// firstprivate variables.
3426/// \code
3427/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3428/// **noalias priv1,..., <tyn> **noalias privn) {
3429/// *priv1 = &.privates.priv1;
3430/// ...;
3431/// *privn = &.privates.privn;
3432/// }
3433/// \endcode
3434static llvm::Value *
3435emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003436 ArrayRef<const Expr *> PrivateVars,
3437 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003438 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003439 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003440 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003441 auto &C = CGM.getContext();
3442 FunctionArgList Args;
3443 ImplicitParamDecl TaskPrivatesArg(
3444 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3445 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3446 Args.push_back(&TaskPrivatesArg);
3447 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3448 unsigned Counter = 1;
3449 for (auto *E: PrivateVars) {
3450 Args.push_back(ImplicitParamDecl::Create(
3451 C, /*DC=*/nullptr, Loc,
3452 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3453 .withConst()
3454 .withRestrict()));
3455 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3456 PrivateVarsPos[VD] = Counter;
3457 ++Counter;
3458 }
3459 for (auto *E : FirstprivateVars) {
3460 Args.push_back(ImplicitParamDecl::Create(
3461 C, /*DC=*/nullptr, Loc,
3462 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3463 .withConst()
3464 .withRestrict()));
3465 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3466 PrivateVarsPos[VD] = Counter;
3467 ++Counter;
3468 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003469 for (auto *E: LastprivateVars) {
3470 Args.push_back(ImplicitParamDecl::Create(
3471 C, /*DC=*/nullptr, Loc,
3472 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3473 .withConst()
3474 .withRestrict()));
3475 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3476 PrivateVarsPos[VD] = Counter;
3477 ++Counter;
3478 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003479 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003480 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003481 auto *TaskPrivatesMapTy =
3482 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3483 auto *TaskPrivatesMap = llvm::Function::Create(
3484 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3485 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003486 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3487 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00003488 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003489 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003490 CodeGenFunction CGF(CGM);
3491 CGF.disableDebugInfo();
3492 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3493 TaskPrivatesMapFnInfo, Args);
3494
3495 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003496 LValue Base = CGF.EmitLoadOfPointerLValue(
3497 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3498 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003499 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3500 Counter = 0;
3501 for (auto *Field : PrivatesQTyRD->fields()) {
3502 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3503 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003504 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003505 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3506 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003507 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003508 ++Counter;
3509 }
3510 CGF.FinishFunction();
3511 return TaskPrivatesMap;
3512}
3513
Alexey Bataev9e034042015-05-05 04:05:12 +00003514static int array_pod_sort_comparator(const PrivateDataTy *P1,
3515 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003516 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3517}
3518
Alexey Bataevf93095a2016-05-05 08:46:22 +00003519/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00003520static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003521 const OMPExecutableDirective &D,
3522 Address KmpTaskSharedsPtr, LValue TDBase,
3523 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3524 QualType SharedsTy, QualType SharedsPtrTy,
3525 const OMPTaskDataTy &Data,
3526 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3527 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003528 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3529 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3530 LValue SrcBase;
3531 if (!Data.FirstprivateVars.empty()) {
3532 SrcBase = CGF.MakeAddrLValue(
3533 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3534 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3535 SharedsTy);
3536 }
3537 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3538 cast<CapturedStmt>(*D.getAssociatedStmt()));
3539 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3540 for (auto &&Pair : Privates) {
3541 auto *VD = Pair.second.PrivateCopy;
3542 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003543 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3544 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003545 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003546 if (auto *Elem = Pair.second.PrivateElemInit) {
3547 auto *OriginalVD = Pair.second.Original;
3548 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3549 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3550 SharedRefLValue = CGF.MakeAddrLValue(
3551 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3552 SharedRefLValue.getType(), AlignmentSource::Decl);
3553 QualType Type = OriginalVD->getType();
3554 if (Type->isArrayType()) {
3555 // Initialize firstprivate array.
3556 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3557 // Perform simple memcpy.
3558 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3559 SharedRefLValue.getAddress(), Type);
3560 } else {
3561 // Initialize firstprivate array using element-by-element
3562 // intialization.
3563 CGF.EmitOMPAggregateAssign(
3564 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3565 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3566 Address SrcElement) {
3567 // Clean up any temporaries needed by the initialization.
3568 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3569 InitScope.addPrivate(
3570 Elem, [SrcElement]() -> Address { return SrcElement; });
3571 (void)InitScope.Privatize();
3572 // Emit initialization for single element.
3573 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3574 CGF, &CapturesInfo);
3575 CGF.EmitAnyExprToMem(Init, DestElement,
3576 Init->getType().getQualifiers(),
3577 /*IsInitializer=*/false);
3578 });
3579 }
3580 } else {
3581 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3582 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3583 return SharedRefLValue.getAddress();
3584 });
3585 (void)InitScope.Privatize();
3586 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3587 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3588 /*capturedByInit=*/false);
3589 }
3590 } else
3591 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3592 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003593 ++FI;
3594 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003595}
3596
3597/// Check if duplication function is required for taskloops.
3598static bool checkInitIsRequired(CodeGenFunction &CGF,
3599 ArrayRef<PrivateDataTy> Privates) {
3600 bool InitRequired = false;
3601 for (auto &&Pair : Privates) {
3602 auto *VD = Pair.second.PrivateCopy;
3603 auto *Init = VD->getAnyInitializer();
3604 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3605 !CGF.isTrivialInitializer(Init));
3606 }
3607 return InitRequired;
3608}
3609
3610
3611/// Emit task_dup function (for initialization of
3612/// private/firstprivate/lastprivate vars and last_iter flag)
3613/// \code
3614/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3615/// lastpriv) {
3616/// // setup lastprivate flag
3617/// task_dst->last = lastpriv;
3618/// // could be constructor calls here...
3619/// }
3620/// \endcode
3621static llvm::Value *
3622emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3623 const OMPExecutableDirective &D,
3624 QualType KmpTaskTWithPrivatesPtrQTy,
3625 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3626 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3627 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3628 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3629 auto &C = CGM.getContext();
3630 FunctionArgList Args;
3631 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc,
3632 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3633 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc,
3634 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3635 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc,
3636 /*Id=*/nullptr, C.IntTy);
3637 Args.push_back(&DstArg);
3638 Args.push_back(&SrcArg);
3639 Args.push_back(&LastprivArg);
3640 auto &TaskDupFnInfo =
3641 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3642 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3643 auto *TaskDup =
3644 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3645 ".omp_task_dup.", &CGM.getModule());
3646 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3647 CodeGenFunction CGF(CGM);
3648 CGF.disableDebugInfo();
3649 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3650
3651 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3652 CGF.GetAddrOfLocalVar(&DstArg),
3653 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3654 // task_dst->liter = lastpriv;
3655 if (WithLastIter) {
3656 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3657 LValue Base = CGF.EmitLValueForField(
3658 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3659 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3660 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3661 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3662 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3663 }
3664
3665 // Emit initial values for private copies (if any).
3666 assert(!Privates.empty());
3667 Address KmpTaskSharedsPtr = Address::invalid();
3668 if (!Data.FirstprivateVars.empty()) {
3669 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3670 CGF.GetAddrOfLocalVar(&SrcArg),
3671 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3672 LValue Base = CGF.EmitLValueForField(
3673 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3674 KmpTaskSharedsPtr = Address(
3675 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3676 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3677 KmpTaskTShareds)),
3678 Loc),
3679 CGF.getNaturalTypeAlignment(SharedsTy));
3680 }
Alexey Bataev8a831592016-05-10 10:36:51 +00003681 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3682 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003683 CGF.FinishFunction();
3684 return TaskDup;
3685}
3686
Alexey Bataev8a831592016-05-10 10:36:51 +00003687/// Checks if destructor function is required to be generated.
3688/// \return true if cleanups are required, false otherwise.
3689static bool
3690checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3691 bool NeedsCleanup = false;
3692 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3693 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3694 for (auto *FD : PrivateRD->fields()) {
3695 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3696 if (NeedsCleanup)
3697 break;
3698 }
3699 return NeedsCleanup;
3700}
3701
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003702CGOpenMPRuntime::TaskResultTy
3703CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3704 const OMPExecutableDirective &D,
3705 llvm::Value *TaskFunction, QualType SharedsTy,
3706 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003707 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003708 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003709 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003710 auto I = Data.PrivateCopies.begin();
3711 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003712 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3713 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003714 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003715 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3716 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003717 ++I;
3718 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003719 I = Data.FirstprivateCopies.begin();
3720 auto IElemInitRef = Data.FirstprivateInits.begin();
3721 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003722 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3723 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003724 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003725 PrivateHelpersTy(
3726 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3727 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003728 ++I;
3729 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003730 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003731 I = Data.LastprivateCopies.begin();
3732 for (auto *E : Data.LastprivateVars) {
3733 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3734 Privates.push_back(std::make_pair(
3735 C.getDeclAlign(VD),
3736 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3737 /*PrivateElemInit=*/nullptr)));
3738 ++I;
3739 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003740 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3741 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003742 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3743 // Build type kmp_routine_entry_t (if not built yet).
3744 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003745 // Build type kmp_task_t (if not built yet).
3746 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003747 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3748 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003749 }
3750 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003751 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003752 auto *KmpTaskTWithPrivatesQTyRD =
3753 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3754 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3755 QualType KmpTaskTWithPrivatesPtrQTy =
3756 C.getPointerType(KmpTaskTWithPrivatesQTy);
3757 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3758 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003759 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003760 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3761
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003762 // Emit initial values for private copies (if any).
3763 llvm::Value *TaskPrivatesMap = nullptr;
3764 auto *TaskPrivatesMapTy =
3765 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3766 3)
3767 ->getType();
3768 if (!Privates.empty()) {
3769 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003770 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3771 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3772 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003773 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3774 TaskPrivatesMap, TaskPrivatesMapTy);
3775 } else {
3776 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3777 cast<llvm::PointerType>(TaskPrivatesMapTy));
3778 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003779 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3780 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003781 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003782 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3783 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3784 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003785
3786 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3787 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3788 // kmp_routine_entry_t *task_entry);
3789 // Task flags. Format is taken from
3790 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3791 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003792 enum {
3793 TiedFlag = 0x1,
3794 FinalFlag = 0x2,
3795 DestructorsFlag = 0x8,
3796 PriorityFlag = 0x20
3797 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003798 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00003799 bool NeedsCleanup = false;
3800 if (!Privates.empty()) {
3801 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3802 if (NeedsCleanup)
3803 Flags = Flags | DestructorsFlag;
3804 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003805 if (Data.Priority.getInt())
3806 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003807 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003808 Data.Final.getPointer()
3809 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00003810 CGF.Builder.getInt32(FinalFlag),
3811 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003812 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003813 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003814 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003815 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3816 getThreadID(CGF, Loc), TaskFlags,
3817 KmpTaskTWithPrivatesTySize, SharedsSize,
3818 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3819 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003820 auto *NewTask = CGF.EmitRuntimeCall(
3821 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003822 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3823 NewTask, KmpTaskTWithPrivatesPtrTy);
3824 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3825 KmpTaskTWithPrivatesQTy);
3826 LValue TDBase =
3827 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003828 // Fill the data in the resulting kmp_task_t record.
3829 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003830 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003831 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003832 KmpTaskSharedsPtr =
3833 Address(CGF.EmitLoadOfScalar(
3834 CGF.EmitLValueForField(
3835 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3836 KmpTaskTShareds)),
3837 Loc),
3838 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003839 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003840 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003841 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00003842 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003843 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003844 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3845 SharedsTy, SharedsPtrTy, Data, Privates,
3846 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003847 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3848 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3849 Result.TaskDupFn = emitTaskDupFunction(
3850 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3851 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3852 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003853 }
3854 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00003855 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3856 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00003857 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00003858 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3859 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3860 if (NeedsCleanup) {
3861 llvm::Value *DestructorFn = emitDestructorsFunction(
3862 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3863 KmpTaskTWithPrivatesQTy);
3864 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3865 LValue DestructorsLV = CGF.EmitLValueForField(
3866 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3867 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3868 DestructorFn, KmpRoutineEntryPtrTy),
3869 DestructorsLV);
3870 }
3871 // Set priority.
3872 if (Data.Priority.getInt()) {
3873 LValue Data2LV = CGF.EmitLValueForField(
3874 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3875 LValue PriorityLV = CGF.EmitLValueForField(
3876 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3877 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3878 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003879 Result.NewTask = NewTask;
3880 Result.TaskEntry = TaskEntry;
3881 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3882 Result.TDBase = TDBase;
3883 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3884 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00003885}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003886
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003887void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3888 const OMPExecutableDirective &D,
3889 llvm::Value *TaskFunction,
3890 QualType SharedsTy, Address Shareds,
3891 const Expr *IfCond,
3892 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003893 if (!CGF.HaveInsertPoint())
3894 return;
3895
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003896 TaskResultTy Result =
3897 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3898 llvm::Value *NewTask = Result.NewTask;
3899 llvm::Value *TaskEntry = Result.TaskEntry;
3900 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3901 LValue TDBase = Result.TDBase;
3902 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00003903 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003904 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003905 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003906 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00003907 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003908 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003909 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003910 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3911 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003912 QualType FlagsTy =
3913 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003914 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3915 if (KmpDependInfoTy.isNull()) {
3916 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3917 KmpDependInfoRD->startDefinition();
3918 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3919 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3920 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3921 KmpDependInfoRD->completeDefinition();
3922 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003923 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003924 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003925 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003926 // Define type kmp_depend_info[<Dependences.size()>];
3927 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003928 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003929 ArrayType::Normal, /*IndexTypeQuals=*/0);
3930 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003931 DependenciesArray =
3932 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003933 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003934 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00003935 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003936 llvm::Value *Size;
3937 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003938 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3939 LValue UpAddrLVal =
3940 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3941 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003942 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003943 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003944 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003945 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3946 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003947 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003948 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003949 auto Base = CGF.MakeAddrLValue(
3950 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003951 KmpDependInfoTy);
3952 // deps[i].base_addr = &<Dependences[i].second>;
3953 auto BaseAddrLVal = CGF.EmitLValueForField(
3954 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003955 CGF.EmitStoreOfScalar(
3956 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3957 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003958 // deps[i].len = sizeof(<Dependences[i].second>);
3959 auto LenLVal = CGF.EmitLValueForField(
3960 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3961 CGF.EmitStoreOfScalar(Size, LenLVal);
3962 // deps[i].flags = <Dependences[i].first>;
3963 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003964 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003965 case OMPC_DEPEND_in:
3966 DepKind = DepIn;
3967 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003968 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003969 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003970 case OMPC_DEPEND_inout:
3971 DepKind = DepInOut;
3972 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003973 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003974 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003975 case OMPC_DEPEND_unknown:
3976 llvm_unreachable("Unknown task dependence type");
3977 }
3978 auto FlagsLVal = CGF.EmitLValueForField(
3979 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3980 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3981 FlagsLVal);
3982 }
John McCall7f416cc2015-09-08 08:05:57 +00003983 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3984 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003985 CGF.VoidPtrTy);
3986 }
3987
Alexey Bataev62b63b12015-03-10 07:28:44 +00003988 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3989 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003990 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3991 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3992 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3993 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003994 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003995 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003996 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3997 llvm::Value *DepTaskArgs[7];
3998 if (NumDependencies) {
3999 DepTaskArgs[0] = UpLoc;
4000 DepTaskArgs[1] = ThreadID;
4001 DepTaskArgs[2] = NewTask;
4002 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4003 DepTaskArgs[4] = DependenciesArray.getPointer();
4004 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4005 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4006 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004007 auto &&ThenCodeGen = [this, Loc, &Data, TDBase, KmpTaskTQTyRD,
Alexey Bataev48591dd2016-04-20 04:01:36 +00004008 NumDependencies, &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004009 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004010 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004011 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4012 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4013 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4014 }
John McCall7f416cc2015-09-08 08:05:57 +00004015 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004016 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004017 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004018 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004019 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004020 TaskArgs);
4021 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004022 // Check if parent region is untied and build return for untied task;
4023 if (auto *Region =
4024 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4025 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004026 };
John McCall7f416cc2015-09-08 08:05:57 +00004027
4028 llvm::Value *DepWaitTaskArgs[6];
4029 if (NumDependencies) {
4030 DepWaitTaskArgs[0] = UpLoc;
4031 DepWaitTaskArgs[1] = ThreadID;
4032 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4033 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4034 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4035 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4036 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004037 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4038 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4039 PrePostActionTy &) {
4040 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004041 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4042 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4043 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4044 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4045 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004046 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004047 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004048 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004049 // Call proxy_task_entry(gtid, new_task);
4050 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4051 CodeGenFunction &CGF, PrePostActionTy &Action) {
4052 Action.Enter(CGF);
4053 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4054 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4055 };
4056
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004057 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4058 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004059 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4060 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004061 RegionCodeGenTy RCG(CodeGen);
4062 CommonActionTy Action(
4063 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4064 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4065 RCG.setAction(Action);
4066 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004067 };
John McCall7f416cc2015-09-08 08:05:57 +00004068
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004069 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004070 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004071 else {
4072 RegionCodeGenTy ThenRCG(ThenCodeGen);
4073 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004074 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004075}
4076
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004077void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4078 const OMPLoopDirective &D,
4079 llvm::Value *TaskFunction,
4080 QualType SharedsTy, Address Shareds,
4081 const Expr *IfCond,
4082 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004083 if (!CGF.HaveInsertPoint())
4084 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004085 TaskResultTy Result =
4086 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004087 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4088 // libcall.
4089 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4090 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4091 // sched, kmp_uint64 grainsize, void *task_dup);
4092 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4093 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4094 llvm::Value *IfVal;
4095 if (IfCond) {
4096 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4097 /*isSigned=*/true);
4098 } else
4099 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4100
4101 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004102 Result.TDBase,
4103 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004104 auto *LBVar =
4105 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4106 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4107 /*IsInitializer=*/true);
4108 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004109 Result.TDBase,
4110 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004111 auto *UBVar =
4112 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4113 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4114 /*IsInitializer=*/true);
4115 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004116 Result.TDBase,
4117 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004118 auto *StVar =
4119 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4120 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4121 /*IsInitializer=*/true);
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004122 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004123 llvm::Value *TaskArgs[] = {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004124 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004125 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004126 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004127 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004128 CGF.IntTy, Data.Schedule.getPointer()
4129 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004130 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004131 Data.Schedule.getPointer()
4132 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004133 /*isSigned=*/false)
4134 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataevf93095a2016-05-05 08:46:22 +00004135 Result.TaskDupFn
4136 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4137 CGF.VoidPtrTy)
4138 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004139 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4140}
4141
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004142/// \brief Emit reduction operation for each element of array (required for
4143/// array sections) LHS op = RHS.
4144/// \param Type Type of array.
4145/// \param LHSVar Variable on the left side of the reduction operation
4146/// (references element of array in original variable).
4147/// \param RHSVar Variable on the right side of the reduction operation
4148/// (references element of array in original variable).
4149/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4150/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004151static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004152 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4153 const VarDecl *RHSVar,
4154 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4155 const Expr *, const Expr *)> &RedOpGen,
4156 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4157 const Expr *UpExpr = nullptr) {
4158 // Perform element-by-element initialization.
4159 QualType ElementTy;
4160 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4161 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4162
4163 // Drill down to the base element type on both arrays.
4164 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4165 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4166
4167 auto RHSBegin = RHSAddr.getPointer();
4168 auto LHSBegin = LHSAddr.getPointer();
4169 // Cast from pointer to array type to pointer to single element.
4170 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4171 // The basic structure here is a while-do loop.
4172 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4173 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4174 auto IsEmpty =
4175 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4176 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4177
4178 // Enter the loop body, making that address the current address.
4179 auto EntryBB = CGF.Builder.GetInsertBlock();
4180 CGF.EmitBlock(BodyBB);
4181
4182 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4183
4184 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4185 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4186 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4187 Address RHSElementCurrent =
4188 Address(RHSElementPHI,
4189 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4190
4191 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4192 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4193 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4194 Address LHSElementCurrent =
4195 Address(LHSElementPHI,
4196 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4197
4198 // Emit copy.
4199 CodeGenFunction::OMPPrivateScope Scope(CGF);
4200 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4201 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4202 Scope.Privatize();
4203 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4204 Scope.ForceCleanup();
4205
4206 // Shift the address forward by one element.
4207 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4208 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4209 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4210 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4211 // Check whether we've reached the end.
4212 auto Done =
4213 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4214 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4215 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4216 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4217
4218 // Done.
4219 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4220}
4221
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004222/// Emit reduction combiner. If the combiner is a simple expression emit it as
4223/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4224/// UDR combiner function.
4225static void emitReductionCombiner(CodeGenFunction &CGF,
4226 const Expr *ReductionOp) {
4227 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4228 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4229 if (auto *DRE =
4230 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4231 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4232 std::pair<llvm::Function *, llvm::Function *> Reduction =
4233 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4234 RValue Func = RValue::get(Reduction.first);
4235 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4236 CGF.EmitIgnoredExpr(ReductionOp);
4237 return;
4238 }
4239 CGF.EmitIgnoredExpr(ReductionOp);
4240}
4241
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004242static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
4243 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004244 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004245 ArrayRef<const Expr *> LHSExprs,
4246 ArrayRef<const Expr *> RHSExprs,
4247 ArrayRef<const Expr *> ReductionOps) {
4248 auto &C = CGM.getContext();
4249
4250 // void reduction_func(void *LHSArg, void *RHSArg);
4251 FunctionArgList Args;
4252 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4253 C.VoidPtrTy);
4254 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4255 C.VoidPtrTy);
4256 Args.push_back(&LHSArg);
4257 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004258 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004259 auto *Fn = llvm::Function::Create(
4260 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4261 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004262 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004263 CodeGenFunction CGF(CGM);
4264 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4265
4266 // Dst = (void*[n])(LHSArg);
4267 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004268 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4269 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4270 ArgsType), CGF.getPointerAlign());
4271 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4272 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4273 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004274
4275 // ...
4276 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4277 // ...
4278 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004279 auto IPriv = Privates.begin();
4280 unsigned Idx = 0;
4281 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004282 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4283 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004284 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004285 });
4286 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4287 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004288 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004289 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004290 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004291 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004292 // Get array size and emit VLA type.
4293 ++Idx;
4294 Address Elem =
4295 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4296 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004297 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4298 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004299 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004300 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004301 CGF.EmitVariablyModifiedType(PrivTy);
4302 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004303 }
4304 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004305 IPriv = Privates.begin();
4306 auto ILHS = LHSExprs.begin();
4307 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004308 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004309 if ((*IPriv)->getType()->isArrayType()) {
4310 // Emit reduction for array section.
4311 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4312 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004313 EmitOMPAggregateReduction(
4314 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4315 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4316 emitReductionCombiner(CGF, E);
4317 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004318 } else
4319 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004320 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004321 ++IPriv;
4322 ++ILHS;
4323 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004324 }
4325 Scope.ForceCleanup();
4326 CGF.FinishFunction();
4327 return Fn;
4328}
4329
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004330static void emitSingleReductionCombiner(CodeGenFunction &CGF,
4331 const Expr *ReductionOp,
4332 const Expr *PrivateRef,
4333 const DeclRefExpr *LHS,
4334 const DeclRefExpr *RHS) {
4335 if (PrivateRef->getType()->isArrayType()) {
4336 // Emit reduction for array section.
4337 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4338 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4339 EmitOMPAggregateReduction(
4340 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4341 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4342 emitReductionCombiner(CGF, ReductionOp);
4343 });
4344 } else
4345 // Emit reduction for array subscript or single variable.
4346 emitReductionCombiner(CGF, ReductionOp);
4347}
4348
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004349void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004350 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004351 ArrayRef<const Expr *> LHSExprs,
4352 ArrayRef<const Expr *> RHSExprs,
4353 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004354 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004355 if (!CGF.HaveInsertPoint())
4356 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004357 // Next code should be emitted for reduction:
4358 //
4359 // static kmp_critical_name lock = { 0 };
4360 //
4361 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4362 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4363 // ...
4364 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4365 // *(Type<n>-1*)rhs[<n>-1]);
4366 // }
4367 //
4368 // ...
4369 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4370 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4371 // RedList, reduce_func, &<lock>)) {
4372 // case 1:
4373 // ...
4374 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4375 // ...
4376 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4377 // break;
4378 // case 2:
4379 // ...
4380 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4381 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004382 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004383 // break;
4384 // default:;
4385 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004386 //
4387 // if SimpleReduction is true, only the next code is generated:
4388 // ...
4389 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4390 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004391
4392 auto &C = CGM.getContext();
4393
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004394 if (SimpleReduction) {
4395 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004396 auto IPriv = Privates.begin();
4397 auto ILHS = LHSExprs.begin();
4398 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004399 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004400 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4401 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004402 ++IPriv;
4403 ++ILHS;
4404 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004405 }
4406 return;
4407 }
4408
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004409 // 1. Build a list of reduction variables.
4410 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004411 auto Size = RHSExprs.size();
4412 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004413 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004414 // Reserve place for array size.
4415 ++Size;
4416 }
4417 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004418 QualType ReductionArrayTy =
4419 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4420 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004421 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004422 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004423 auto IPriv = Privates.begin();
4424 unsigned Idx = 0;
4425 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004426 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004427 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004428 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004429 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004430 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4431 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004432 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004433 // Store array size.
4434 ++Idx;
4435 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4436 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004437 llvm::Value *Size = CGF.Builder.CreateIntCast(
4438 CGF.getVLASize(
4439 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4440 .first,
4441 CGF.SizeTy, /*isSigned=*/false);
4442 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4443 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004444 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004445 }
4446
4447 // 2. Emit reduce_func().
4448 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004449 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4450 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004451
4452 // 3. Create static kmp_critical_name lock = { 0 };
4453 auto *Lock = getCriticalRegionLock(".reduction");
4454
4455 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4456 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004457 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004458 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004459 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004460 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4461 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004462 llvm::Value *Args[] = {
4463 IdentTLoc, // ident_t *<loc>
4464 ThreadId, // i32 <gtid>
4465 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4466 ReductionArrayTySize, // size_type sizeof(RedList)
4467 RL, // void *RedList
4468 ReductionFn, // void (*) (void *, void *) <reduce_func>
4469 Lock // kmp_critical_name *&<lock>
4470 };
4471 auto Res = CGF.EmitRuntimeCall(
4472 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4473 : OMPRTL__kmpc_reduce),
4474 Args);
4475
4476 // 5. Build switch(res)
4477 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4478 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4479
4480 // 6. Build case 1:
4481 // ...
4482 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4483 // ...
4484 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4485 // break;
4486 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4487 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4488 CGF.EmitBlock(Case1BB);
4489
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004490 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4491 llvm::Value *EndArgs[] = {
4492 IdentTLoc, // ident_t *<loc>
4493 ThreadId, // i32 <gtid>
4494 Lock // kmp_critical_name *&<lock>
4495 };
4496 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4497 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004498 auto IPriv = Privates.begin();
4499 auto ILHS = LHSExprs.begin();
4500 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004501 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004502 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4503 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004504 ++IPriv;
4505 ++ILHS;
4506 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004507 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004508 };
4509 RegionCodeGenTy RCG(CodeGen);
4510 CommonActionTy Action(
4511 nullptr, llvm::None,
4512 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4513 : OMPRTL__kmpc_end_reduce),
4514 EndArgs);
4515 RCG.setAction(Action);
4516 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004517
4518 CGF.EmitBranch(DefaultBB);
4519
4520 // 7. Build case 2:
4521 // ...
4522 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4523 // ...
4524 // break;
4525 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4526 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4527 CGF.EmitBlock(Case2BB);
4528
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004529 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4530 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004531 auto ILHS = LHSExprs.begin();
4532 auto IRHS = RHSExprs.begin();
4533 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004534 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004535 const Expr *XExpr = nullptr;
4536 const Expr *EExpr = nullptr;
4537 const Expr *UpExpr = nullptr;
4538 BinaryOperatorKind BO = BO_Comma;
4539 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4540 if (BO->getOpcode() == BO_Assign) {
4541 XExpr = BO->getLHS();
4542 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004543 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004544 }
4545 // Try to emit update expression as a simple atomic.
4546 auto *RHSExpr = UpExpr;
4547 if (RHSExpr) {
4548 // Analyze RHS part of the whole expression.
4549 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4550 RHSExpr->IgnoreParenImpCasts())) {
4551 // If this is a conditional operator, analyze its condition for
4552 // min/max reduction operator.
4553 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004554 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004555 if (auto *BORHS =
4556 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4557 EExpr = BORHS->getRHS();
4558 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004559 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004560 }
4561 if (XExpr) {
4562 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4563 auto &&AtomicRedGen = [BO, VD, IPriv,
4564 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4565 const Expr *EExpr, const Expr *UpExpr) {
4566 LValue X = CGF.EmitLValue(XExpr);
4567 RValue E;
4568 if (EExpr)
4569 E = CGF.EmitAnyExpr(EExpr);
4570 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004571 X, E, BO, /*IsXLHSInRHSPart=*/true,
4572 llvm::AtomicOrdering::Monotonic, Loc,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004573 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
4574 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4575 PrivateScope.addPrivate(
4576 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4577 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4578 CGF.emitOMPSimpleStore(
4579 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4580 VD->getType().getNonReferenceType(), Loc);
4581 return LHSTemp;
4582 });
4583 (void)PrivateScope.Privatize();
4584 return CGF.EmitAnyExpr(UpExpr);
4585 });
4586 };
4587 if ((*IPriv)->getType()->isArrayType()) {
4588 // Emit atomic reduction for array section.
4589 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4590 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4591 AtomicRedGen, XExpr, EExpr, UpExpr);
4592 } else
4593 // Emit atomic reduction for array subscript or single variable.
4594 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4595 } else {
4596 // Emit as a critical region.
4597 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4598 const Expr *, const Expr *) {
4599 auto &RT = CGF.CGM.getOpenMPRuntime();
4600 RT.emitCriticalRegion(
4601 CGF, ".atomic_reduction",
4602 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4603 Action.Enter(CGF);
4604 emitReductionCombiner(CGF, E);
4605 },
4606 Loc);
4607 };
4608 if ((*IPriv)->getType()->isArrayType()) {
4609 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4610 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4611 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4612 CritRedGen);
4613 } else
4614 CritRedGen(CGF, nullptr, nullptr, nullptr);
4615 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004616 ++ILHS;
4617 ++IRHS;
4618 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004619 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004620 };
4621 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4622 if (!WithNowait) {
4623 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4624 llvm::Value *EndArgs[] = {
4625 IdentTLoc, // ident_t *<loc>
4626 ThreadId, // i32 <gtid>
4627 Lock // kmp_critical_name *&<lock>
4628 };
4629 CommonActionTy Action(nullptr, llvm::None,
4630 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4631 EndArgs);
4632 AtomicRCG.setAction(Action);
4633 AtomicRCG(CGF);
4634 } else
4635 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004636
4637 CGF.EmitBranch(DefaultBB);
4638 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4639}
4640
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004641void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4642 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004643 if (!CGF.HaveInsertPoint())
4644 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004645 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4646 // global_tid);
4647 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4648 // Ignore return result until untied tasks are supported.
4649 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004650 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4651 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004652}
4653
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004654void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004655 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004656 const RegionCodeGenTy &CodeGen,
4657 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004658 if (!CGF.HaveInsertPoint())
4659 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004660 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004661 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004662}
4663
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004664namespace {
4665enum RTCancelKind {
4666 CancelNoreq = 0,
4667 CancelParallel = 1,
4668 CancelLoop = 2,
4669 CancelSections = 3,
4670 CancelTaskgroup = 4
4671};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004672} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004673
4674static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4675 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004676 if (CancelRegion == OMPD_parallel)
4677 CancelKind = CancelParallel;
4678 else if (CancelRegion == OMPD_for)
4679 CancelKind = CancelLoop;
4680 else if (CancelRegion == OMPD_sections)
4681 CancelKind = CancelSections;
4682 else {
4683 assert(CancelRegion == OMPD_taskgroup);
4684 CancelKind = CancelTaskgroup;
4685 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004686 return CancelKind;
4687}
4688
4689void CGOpenMPRuntime::emitCancellationPointCall(
4690 CodeGenFunction &CGF, SourceLocation Loc,
4691 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004692 if (!CGF.HaveInsertPoint())
4693 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004694 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4695 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004696 if (auto *OMPRegionInfo =
4697 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004698 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004699 llvm::Value *Args[] = {
4700 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4701 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004702 // Ignore return result until untied tasks are supported.
4703 auto *Result = CGF.EmitRuntimeCall(
4704 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4705 // if (__kmpc_cancellationpoint()) {
4706 // __kmpc_cancel_barrier();
4707 // exit from construct;
4708 // }
4709 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4710 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4711 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4712 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4713 CGF.EmitBlock(ExitBB);
4714 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004715 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004716 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004717 auto CancelDest =
4718 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004719 CGF.EmitBranchThroughCleanup(CancelDest);
4720 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4721 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004722 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004723}
4724
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004725void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004726 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004727 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004728 if (!CGF.HaveInsertPoint())
4729 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004730 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4731 // kmp_int32 cncl_kind);
4732 if (auto *OMPRegionInfo =
4733 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004734 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4735 PrePostActionTy &) {
4736 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004737 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004738 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004739 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4740 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004741 auto *Result = CGF.EmitRuntimeCall(
4742 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004743 // if (__kmpc_cancel()) {
4744 // __kmpc_cancel_barrier();
4745 // exit from construct;
4746 // }
4747 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4748 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4749 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4750 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4751 CGF.EmitBlock(ExitBB);
4752 // __kmpc_cancel_barrier();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004753 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev87933c72015-09-18 08:07:34 +00004754 // exit from construct;
4755 auto CancelDest =
4756 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4757 CGF.EmitBranchThroughCleanup(CancelDest);
4758 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4759 };
4760 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004761 emitOMPIfClause(CGF, IfCond, ThenGen,
4762 [](CodeGenFunction &, PrePostActionTy &) {});
4763 else {
4764 RegionCodeGenTy ThenRCG(ThenGen);
4765 ThenRCG(CGF);
4766 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004767 }
4768}
Samuel Antaobed3c462015-10-02 16:14:20 +00004769
Samuel Antaoee8fb302016-01-06 13:42:12 +00004770/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004771/// consists of the file and device IDs as well as line number associated with
4772/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004773static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4774 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004775 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004776
4777 auto &SM = C.getSourceManager();
4778
4779 // The loc should be always valid and have a file ID (the user cannot use
4780 // #pragma directives in macros)
4781
4782 assert(Loc.isValid() && "Source location is expected to be always valid.");
4783 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4784
4785 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4786 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4787
4788 llvm::sys::fs::UniqueID ID;
4789 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4790 llvm_unreachable("Source file with target region no longer exists!");
4791
4792 DeviceID = ID.getDevice();
4793 FileID = ID.getFile();
4794 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004795}
4796
4797void CGOpenMPRuntime::emitTargetOutlinedFunction(
4798 const OMPExecutableDirective &D, StringRef ParentName,
4799 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004800 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004801 assert(!ParentName.empty() && "Invalid target region parent name!");
4802
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004803 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4804 IsOffloadEntry, CodeGen);
4805}
4806
4807void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4808 const OMPExecutableDirective &D, StringRef ParentName,
4809 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4810 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004811 // Create a unique name for the entry function using the source location
4812 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004813 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004814 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004815 //
4816 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004817 // mangled name of the function that encloses the target region and BB is the
4818 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004819
4820 unsigned DeviceID;
4821 unsigned FileID;
4822 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004823 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004824 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004825 SmallString<64> EntryFnName;
4826 {
4827 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004828 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4829 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004830 }
4831
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004832 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4833
Samuel Antaobed3c462015-10-02 16:14:20 +00004834 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004835 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004836 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004837
Samuel Antao6d004262016-06-16 18:39:34 +00004838 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004839
4840 // If this target outline function is not an offload entry, we don't need to
4841 // register it.
4842 if (!IsOffloadEntry)
4843 return;
4844
4845 // The target region ID is used by the runtime library to identify the current
4846 // target region, so it only has to be unique and not necessarily point to
4847 // anything. It could be the pointer to the outlined function that implements
4848 // the target region, but we aren't using that so that the compiler doesn't
4849 // need to keep that, and could therefore inline the host function if proven
4850 // worthwhile during optimization. In the other hand, if emitting code for the
4851 // device, the ID has to be the function address so that it can retrieved from
4852 // the offloading entry and launched by the runtime library. We also mark the
4853 // outlined function to have external linkage in case we are emitting code for
4854 // the device, because these functions will be entry points to the device.
4855
4856 if (CGM.getLangOpts().OpenMPIsDevice) {
4857 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4858 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4859 } else
4860 OutlinedFnID = new llvm::GlobalVariable(
4861 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4862 llvm::GlobalValue::PrivateLinkage,
4863 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4864
4865 // Register the information for the entry associated with this target region.
4866 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00004867 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
4868 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00004869}
4870
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004871/// discard all CompoundStmts intervening between two constructs
4872static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4873 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4874 Body = CS->body_front();
4875
4876 return Body;
4877}
4878
Samuel Antaob68e2db2016-03-03 16:20:23 +00004879/// \brief Emit the num_teams clause of an enclosed teams directive at the
4880/// target region scope. If there is no teams directive associated with the
4881/// target directive, or if there is no num_teams clause associated with the
4882/// enclosed teams directive, return nullptr.
4883static llvm::Value *
4884emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4885 CodeGenFunction &CGF,
4886 const OMPExecutableDirective &D) {
4887
4888 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4889 "teams directive expected to be "
4890 "emitted only for the host!");
4891
4892 // FIXME: For the moment we do not support combined directives with target and
4893 // teams, so we do not expect to get any num_teams clause in the provided
4894 // directive. Once we support that, this assertion can be replaced by the
4895 // actual emission of the clause expression.
4896 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4897 "Not expecting clause in directive.");
4898
4899 // If the current target region has a teams region enclosed, we need to get
4900 // the number of teams to pass to the runtime function call. This is done
4901 // by generating the expression in a inlined region. This is required because
4902 // the expression is captured in the enclosing target environment when the
4903 // teams directive is not combined with target.
4904
4905 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4906
4907 // FIXME: Accommodate other combined directives with teams when they become
4908 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004909 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4910 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004911 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4912 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4913 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4914 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4915 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4916 /*IsSigned=*/true);
4917 }
4918
4919 // If we have an enclosed teams directive but no num_teams clause we use
4920 // the default value 0.
4921 return CGF.Builder.getInt32(0);
4922 }
4923
4924 // No teams associated with the directive.
4925 return nullptr;
4926}
4927
4928/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4929/// target region scope. If there is no teams directive associated with the
4930/// target directive, or if there is no thread_limit clause associated with the
4931/// enclosed teams directive, return nullptr.
4932static llvm::Value *
4933emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4934 CodeGenFunction &CGF,
4935 const OMPExecutableDirective &D) {
4936
4937 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4938 "teams directive expected to be "
4939 "emitted only for the host!");
4940
4941 // FIXME: For the moment we do not support combined directives with target and
4942 // teams, so we do not expect to get any thread_limit clause in the provided
4943 // directive. Once we support that, this assertion can be replaced by the
4944 // actual emission of the clause expression.
4945 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4946 "Not expecting clause in directive.");
4947
4948 // If the current target region has a teams region enclosed, we need to get
4949 // the thread limit to pass to the runtime function call. This is done
4950 // by generating the expression in a inlined region. This is required because
4951 // the expression is captured in the enclosing target environment when the
4952 // teams directive is not combined with target.
4953
4954 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4955
4956 // FIXME: Accommodate other combined directives with teams when they become
4957 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004958 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4959 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004960 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4961 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4962 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4963 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4964 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4965 /*IsSigned=*/true);
4966 }
4967
4968 // If we have an enclosed teams directive but no thread_limit clause we use
4969 // the default value 0.
4970 return CGF.Builder.getInt32(0);
4971 }
4972
4973 // No teams associated with the directive.
4974 return nullptr;
4975}
4976
Samuel Antao86ace552016-04-27 22:40:57 +00004977namespace {
4978// \brief Utility to handle information from clauses associated with a given
4979// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
4980// It provides a convenient interface to obtain the information and generate
4981// code for that information.
4982class MappableExprsHandler {
4983public:
4984 /// \brief Values for bit flags used to specify the mapping type for
4985 /// offloading.
4986 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00004987 /// \brief Allocate memory on the device and move data from host to device.
4988 OMP_MAP_TO = 0x01,
4989 /// \brief Allocate memory on the device and move data from device to host.
4990 OMP_MAP_FROM = 0x02,
4991 /// \brief Always perform the requested mapping action on the element, even
4992 /// if it was already mapped before.
4993 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00004994 /// \brief Delete the element from the device environment, ignoring the
4995 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00004996 OMP_MAP_DELETE = 0x08,
4997 /// \brief The element being mapped is a pointer, therefore the pointee
4998 /// should be mapped as well.
4999 OMP_MAP_IS_PTR = 0x10,
5000 /// \brief This flags signals that an argument is the first one relating to
5001 /// a map/private clause expression. For some cases a single
5002 /// map/privatization results in multiple arguments passed to the runtime
5003 /// library.
5004 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005005 /// \brief Signal that the runtime library has to return the device pointer
5006 /// in the current position for the data being mapped.
5007 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005008 /// \brief This flag signals that the reference being passed is a pointer to
5009 /// private data.
5010 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005011 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005012 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005013 };
5014
Samuel Antaocc10b852016-07-28 14:23:26 +00005015 /// Class that associates information with a base pointer to be passed to the
5016 /// runtime library.
5017 class BasePointerInfo {
5018 /// The base pointer.
5019 llvm::Value *Ptr = nullptr;
5020 /// The base declaration that refers to this device pointer, or null if
5021 /// there is none.
5022 const ValueDecl *DevPtrDecl = nullptr;
5023
5024 public:
5025 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5026 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5027 llvm::Value *operator*() const { return Ptr; }
5028 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5029 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5030 };
5031
5032 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005033 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5034 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5035
5036private:
5037 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005038 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005039
5040 /// \brief Function the directive is being generated for.
5041 CodeGenFunction &CGF;
5042
Samuel Antaod486f842016-05-26 16:53:38 +00005043 /// \brief Set of all first private variables in the current directive.
5044 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5045
Samuel Antao6890b092016-07-28 14:25:09 +00005046 /// Map between device pointer declarations and their expression components.
5047 /// The key value for declarations in 'this' is null.
5048 llvm::DenseMap<
5049 const ValueDecl *,
5050 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5051 DevPointersMap;
5052
Samuel Antao86ace552016-04-27 22:40:57 +00005053 llvm::Value *getExprTypeSize(const Expr *E) const {
5054 auto ExprTy = E->getType().getCanonicalType();
5055
5056 // Reference types are ignored for mapping purposes.
5057 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5058 ExprTy = RefTy->getPointeeType().getCanonicalType();
5059
5060 // Given that an array section is considered a built-in type, we need to
5061 // do the calculation based on the length of the section instead of relying
5062 // on CGF.getTypeSize(E->getType()).
5063 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5064 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5065 OAE->getBase()->IgnoreParenImpCasts())
5066 .getCanonicalType();
5067
5068 // If there is no length associated with the expression, that means we
5069 // are using the whole length of the base.
5070 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5071 return CGF.getTypeSize(BaseTy);
5072
5073 llvm::Value *ElemSize;
5074 if (auto *PTy = BaseTy->getAs<PointerType>())
5075 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5076 else {
5077 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5078 assert(ATy && "Expecting array type if not a pointer type.");
5079 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5080 }
5081
5082 // If we don't have a length at this point, that is because we have an
5083 // array section with a single element.
5084 if (!OAE->getLength())
5085 return ElemSize;
5086
5087 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5088 LengthVal =
5089 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5090 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5091 }
5092 return CGF.getTypeSize(ExprTy);
5093 }
5094
5095 /// \brief Return the corresponding bits for a given map clause modifier. Add
5096 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00005097 /// map as the first one of a series of maps that relate to the same map
5098 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00005099 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5100 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00005101 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00005102 unsigned Bits = 0u;
5103 switch (MapType) {
5104 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00005105 case OMPC_MAP_release:
5106 // alloc and release is the default behavior in the runtime library, i.e.
5107 // if we don't pass any bits alloc/release that is what the runtime is
5108 // going to do. Therefore, we don't need to signal anything for these two
5109 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00005110 break;
5111 case OMPC_MAP_to:
5112 Bits = OMP_MAP_TO;
5113 break;
5114 case OMPC_MAP_from:
5115 Bits = OMP_MAP_FROM;
5116 break;
5117 case OMPC_MAP_tofrom:
5118 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5119 break;
5120 case OMPC_MAP_delete:
5121 Bits = OMP_MAP_DELETE;
5122 break;
Samuel Antao86ace552016-04-27 22:40:57 +00005123 default:
5124 llvm_unreachable("Unexpected map type!");
5125 break;
5126 }
5127 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00005128 Bits |= OMP_MAP_IS_PTR;
5129 if (AddIsFirstFlag)
5130 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00005131 if (MapTypeModifier == OMPC_MAP_always)
5132 Bits |= OMP_MAP_ALWAYS;
5133 return Bits;
5134 }
5135
5136 /// \brief Return true if the provided expression is a final array section. A
5137 /// final array section, is one whose length can't be proved to be one.
5138 bool isFinalArraySectionExpression(const Expr *E) const {
5139 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5140
5141 // It is not an array section and therefore not a unity-size one.
5142 if (!OASE)
5143 return false;
5144
5145 // An array section with no colon always refer to a single element.
5146 if (OASE->getColonLoc().isInvalid())
5147 return false;
5148
5149 auto *Length = OASE->getLength();
5150
5151 // If we don't have a length we have to check if the array has size 1
5152 // for this dimension. Also, we should always expect a length if the
5153 // base type is pointer.
5154 if (!Length) {
5155 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5156 OASE->getBase()->IgnoreParenImpCasts())
5157 .getCanonicalType();
5158 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5159 return ATy->getSize().getSExtValue() != 1;
5160 // If we don't have a constant dimension length, we have to consider
5161 // the current section as having any size, so it is not necessarily
5162 // unitary. If it happen to be unity size, that's user fault.
5163 return true;
5164 }
5165
5166 // Check if the length evaluates to 1.
5167 llvm::APSInt ConstLength;
5168 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5169 return true; // Can have more that size 1.
5170
5171 return ConstLength.getSExtValue() != 1;
5172 }
5173
5174 /// \brief Generate the base pointers, section pointers, sizes and map type
5175 /// bits for the provided map type, map modifier, and expression components.
5176 /// \a IsFirstComponent should be set to true if the provided set of
5177 /// components is the first associated with a capture.
5178 void generateInfoForComponentList(
5179 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5180 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00005181 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005182 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5183 bool IsFirstComponentList) const {
5184
5185 // The following summarizes what has to be generated for each map and the
5186 // types bellow. The generated information is expressed in this order:
5187 // base pointer, section pointer, size, flags
5188 // (to add to the ones that come from the map type and modifier).
5189 //
5190 // double d;
5191 // int i[100];
5192 // float *p;
5193 //
5194 // struct S1 {
5195 // int i;
5196 // float f[50];
5197 // }
5198 // struct S2 {
5199 // int i;
5200 // float f[50];
5201 // S1 s;
5202 // double *p;
5203 // struct S2 *ps;
5204 // }
5205 // S2 s;
5206 // S2 *ps;
5207 //
5208 // map(d)
5209 // &d, &d, sizeof(double), noflags
5210 //
5211 // map(i)
5212 // &i, &i, 100*sizeof(int), noflags
5213 //
5214 // map(i[1:23])
5215 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5216 //
5217 // map(p)
5218 // &p, &p, sizeof(float*), noflags
5219 //
5220 // map(p[1:24])
5221 // p, &p[1], 24*sizeof(float), noflags
5222 //
5223 // map(s)
5224 // &s, &s, sizeof(S2), noflags
5225 //
5226 // map(s.i)
5227 // &s, &(s.i), sizeof(int), noflags
5228 //
5229 // map(s.s.f)
5230 // &s, &(s.i.f), 50*sizeof(int), noflags
5231 //
5232 // map(s.p)
5233 // &s, &(s.p), sizeof(double*), noflags
5234 //
5235 // map(s.p[:22], s.a s.b)
5236 // &s, &(s.p), sizeof(double*), noflags
5237 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5238 //
5239 // map(s.ps)
5240 // &s, &(s.ps), sizeof(S2*), noflags
5241 //
5242 // map(s.ps->s.i)
5243 // &s, &(s.ps), sizeof(S2*), noflags
5244 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5245 //
5246 // map(s.ps->ps)
5247 // &s, &(s.ps), sizeof(S2*), noflags
5248 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5249 //
5250 // map(s.ps->ps->ps)
5251 // &s, &(s.ps), sizeof(S2*), noflags
5252 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5253 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5254 //
5255 // map(s.ps->ps->s.f[:22])
5256 // &s, &(s.ps), sizeof(S2*), noflags
5257 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5258 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5259 //
5260 // map(ps)
5261 // &ps, &ps, sizeof(S2*), noflags
5262 //
5263 // map(ps->i)
5264 // ps, &(ps->i), sizeof(int), noflags
5265 //
5266 // map(ps->s.f)
5267 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5268 //
5269 // map(ps->p)
5270 // ps, &(ps->p), sizeof(double*), noflags
5271 //
5272 // map(ps->p[:22])
5273 // ps, &(ps->p), sizeof(double*), noflags
5274 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5275 //
5276 // map(ps->ps)
5277 // ps, &(ps->ps), sizeof(S2*), noflags
5278 //
5279 // map(ps->ps->s.i)
5280 // ps, &(ps->ps), sizeof(S2*), noflags
5281 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5282 //
5283 // map(ps->ps->ps)
5284 // ps, &(ps->ps), sizeof(S2*), noflags
5285 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5286 //
5287 // map(ps->ps->ps->ps)
5288 // ps, &(ps->ps), sizeof(S2*), noflags
5289 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5290 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5291 //
5292 // map(ps->ps->ps->s.f[:22])
5293 // ps, &(ps->ps), sizeof(S2*), noflags
5294 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5295 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5296 // extra_flag
5297
5298 // Track if the map information being generated is the first for a capture.
5299 bool IsCaptureFirstInfo = IsFirstComponentList;
5300
5301 // Scan the components from the base to the complete expression.
5302 auto CI = Components.rbegin();
5303 auto CE = Components.rend();
5304 auto I = CI;
5305
5306 // Track if the map information being generated is the first for a list of
5307 // components.
5308 bool IsExpressionFirstInfo = true;
5309 llvm::Value *BP = nullptr;
5310
5311 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5312 // The base is the 'this' pointer. The content of the pointer is going
5313 // to be the base of the field being mapped.
5314 BP = CGF.EmitScalarExpr(ME->getBase());
5315 } else {
5316 // The base is the reference to the variable.
5317 // BP = &Var.
5318 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5319 .getPointer();
5320
5321 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00005322 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00005323 // reference. References are ignored for mapping purposes.
5324 QualType Ty =
5325 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5326 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5327 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00005328 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00005329 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00005330 .getPointer();
5331
5332 // We do not need to generate individual map information for the
5333 // pointer, it can be associated with the combined storage.
5334 ++I;
5335 }
5336 }
5337
5338 for (; I != CE; ++I) {
5339 auto Next = std::next(I);
5340
5341 // We need to generate the addresses and sizes if this is the last
5342 // component, if the component is a pointer or if it is an array section
5343 // whose length can't be proved to be one. If this is a pointer, it
5344 // becomes the base address for the following components.
5345
5346 // A final array section, is one whose length can't be proved to be one.
5347 bool IsFinalArraySection =
5348 isFinalArraySectionExpression(I->getAssociatedExpression());
5349
5350 // Get information on whether the element is a pointer. Have to do a
5351 // special treatment for array sections given that they are built-in
5352 // types.
5353 const auto *OASE =
5354 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5355 bool IsPointer =
5356 (OASE &&
5357 OMPArraySectionExpr::getBaseOriginalType(OASE)
5358 .getCanonicalType()
5359 ->isAnyPointerType()) ||
5360 I->getAssociatedExpression()->getType()->isAnyPointerType();
5361
5362 if (Next == CE || IsPointer || IsFinalArraySection) {
5363
5364 // If this is not the last component, we expect the pointer to be
5365 // associated with an array expression or member expression.
5366 assert((Next == CE ||
5367 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5368 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5369 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5370 "Unexpected expression");
5371
Samuel Antao86ace552016-04-27 22:40:57 +00005372 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5373 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5374
Samuel Antao03a3cec2016-07-27 22:52:16 +00005375 // If we have a member expression and the current component is a
5376 // reference, we have to map the reference too. Whenever we have a
5377 // reference, the section that reference refers to is going to be a
5378 // load instruction from the storage assigned to the reference.
5379 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5380 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5381 auto *LI = cast<llvm::LoadInst>(LB);
5382 auto *RefAddr = LI->getPointerOperand();
5383
5384 BasePointers.push_back(BP);
5385 Pointers.push_back(RefAddr);
5386 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5387 Types.push_back(getMapTypeBits(
5388 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5389 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5390 IsExpressionFirstInfo = false;
5391 IsCaptureFirstInfo = false;
5392 // The reference will be the next base address.
5393 BP = RefAddr;
5394 }
5395
5396 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00005397 Pointers.push_back(LB);
5398 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00005399
Samuel Antao6782e942016-05-26 16:48:10 +00005400 // We need to add a pointer flag for each map that comes from the
5401 // same expression except for the first one. We also need to signal
5402 // this map is the first one that relates with the current capture
5403 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00005404 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5405 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00005406 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00005407
5408 // If we have a final array section, we are done with this expression.
5409 if (IsFinalArraySection)
5410 break;
5411
5412 // The pointer becomes the base for the next element.
5413 if (Next != CE)
5414 BP = LB;
5415
5416 IsExpressionFirstInfo = false;
5417 IsCaptureFirstInfo = false;
5418 continue;
5419 }
5420 }
5421 }
5422
Samuel Antaod486f842016-05-26 16:53:38 +00005423 /// \brief Return the adjusted map modifiers if the declaration a capture
5424 /// refers to appears in a first-private clause. This is expected to be used
5425 /// only with directives that start with 'target'.
5426 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5427 unsigned CurrentModifiers) {
5428 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5429
5430 // A first private variable captured by reference will use only the
5431 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5432 // declaration is known as first-private in this handler.
5433 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5434 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5435 MappableExprsHandler::OMP_MAP_TO;
5436
5437 // We didn't modify anything.
5438 return CurrentModifiers;
5439 }
5440
Samuel Antao86ace552016-04-27 22:40:57 +00005441public:
5442 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00005443 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00005444 // Extract firstprivate clause information.
5445 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5446 for (const auto *D : C->varlists())
5447 FirstPrivateDecls.insert(
5448 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00005449 // Extract device pointer clause information.
5450 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5451 for (auto L : C->component_lists())
5452 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00005453 }
Samuel Antao86ace552016-04-27 22:40:57 +00005454
5455 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00005456 /// types for the extracted mappable expressions. Also, for each item that
5457 /// relates with a device pointer, a pair of the relevant declaration and
5458 /// index where it occurs is appended to the device pointers info array.
5459 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005460 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5461 MapFlagsArrayTy &Types) const {
5462 BasePointers.clear();
5463 Pointers.clear();
5464 Sizes.clear();
5465 Types.clear();
5466
5467 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00005468 /// Kind that defines how a device pointer has to be returned.
5469 enum ReturnPointerKind {
5470 // Don't have to return any pointer.
5471 RPK_None,
5472 // Pointer is the base of the declaration.
5473 RPK_Base,
5474 // Pointer is a member of the base declaration - 'this'
5475 RPK_Member,
5476 // Pointer is a reference and a member of the base declaration - 'this'
5477 RPK_MemberReference,
5478 };
Samuel Antao86ace552016-04-27 22:40:57 +00005479 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00005480 OpenMPMapClauseKind MapType;
5481 OpenMPMapClauseKind MapTypeModifier;
5482 ReturnPointerKind ReturnDevicePointer;
5483
5484 MapInfo()
5485 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5486 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00005487 MapInfo(
5488 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5489 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5490 ReturnPointerKind ReturnDevicePointer)
5491 : Components(Components), MapType(MapType),
5492 MapTypeModifier(MapTypeModifier),
5493 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00005494 };
5495
5496 // We have to process the component lists that relate with the same
5497 // declaration in a single chunk so that we can generate the map flags
5498 // correctly. Therefore, we organize all lists in a map.
5499 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00005500
5501 // Helper function to fill the information map for the different supported
5502 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00005503 auto &&InfoGen = [&Info](
5504 const ValueDecl *D,
5505 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5506 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005507 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005508 const ValueDecl *VD =
5509 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5510 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5511 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00005512
Paul Robinson78fb1322016-08-01 22:12:46 +00005513 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005514 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005515 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005516 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5517 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005518 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005519 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005520 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5521 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005522 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005523 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005524 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5525 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00005526
Samuel Antaocc10b852016-07-28 14:23:26 +00005527 // Look at the use_device_ptr clause information and mark the existing map
5528 // entries as such. If there is no map information for an entry in the
5529 // use_device_ptr list, we create one with map type 'alloc' and zero size
5530 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00005531 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005532 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00005533 for (auto L : C->component_lists()) {
5534 assert(!L.second.empty() && "Not expecting empty list of components!");
5535 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5536 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5537 auto *IE = L.second.back().getAssociatedExpression();
5538 // If the first component is a member expression, we have to look into
5539 // 'this', which maps to null in the map of map information. Otherwise
5540 // look directly for the information.
5541 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5542
5543 // We potentially have map information for this declaration already.
5544 // Look for the first set of components that refer to it.
5545 if (It != Info.end()) {
5546 auto CI = std::find_if(
5547 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5548 return MI.Components.back().getAssociatedDeclaration() == VD;
5549 });
5550 // If we found a map entry, signal that the pointer has to be returned
5551 // and move on to the next declaration.
5552 if (CI != It->second.end()) {
5553 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5554 ? (VD->getType()->isReferenceType()
5555 ? MapInfo::RPK_MemberReference
5556 : MapInfo::RPK_Member)
5557 : MapInfo::RPK_Base;
5558 continue;
5559 }
5560 }
5561
5562 // We didn't find any match in our map information - generate a zero
5563 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00005564 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00005565 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00005566 this->CGF
5567 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00005568 .getScalarVal();
5569 BasePointers.push_back({Ptr, VD});
5570 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00005571 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00005572 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5573 }
5574
Samuel Antao86ace552016-04-27 22:40:57 +00005575 for (auto &M : Info) {
5576 // We need to know when we generate information for the first component
5577 // associated with a capture, because the mapping flags depend on it.
5578 bool IsFirstComponentList = true;
5579 for (MapInfo &L : M.second) {
5580 assert(!L.Components.empty() &&
5581 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00005582
5583 // Remember the current base pointer index.
5584 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00005585 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00005586 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5587 L.Components, BasePointers, Pointers,
5588 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00005589
5590 // If this entry relates with a device pointer, set the relevant
5591 // declaration and add the 'return pointer' flag.
5592 if (IsFirstComponentList &&
5593 L.ReturnDevicePointer != MapInfo::RPK_None) {
5594 // If the pointer is not the base of the map, we need to skip the
5595 // base. If it is a reference in a member field, we also need to skip
5596 // the map of the reference.
5597 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5598 ++CurrentBasePointersIdx;
5599 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5600 ++CurrentBasePointersIdx;
5601 }
5602 assert(BasePointers.size() > CurrentBasePointersIdx &&
5603 "Unexpected number of mapped base pointers.");
5604
5605 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5606 assert(RelevantVD &&
5607 "No relevant declaration related with device pointer??");
5608
5609 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5610 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5611 }
Samuel Antao86ace552016-04-27 22:40:57 +00005612 IsFirstComponentList = false;
5613 }
5614 }
5615 }
5616
5617 /// \brief Generate the base pointers, section pointers, sizes and map types
5618 /// associated to a given capture.
5619 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00005620 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005621 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005622 MapValuesArrayTy &Pointers,
5623 MapValuesArrayTy &Sizes,
5624 MapFlagsArrayTy &Types) const {
5625 assert(!Cap->capturesVariableArrayType() &&
5626 "Not expecting to generate map info for a variable array type!");
5627
5628 BasePointers.clear();
5629 Pointers.clear();
5630 Sizes.clear();
5631 Types.clear();
5632
Samuel Antao6890b092016-07-28 14:25:09 +00005633 // We need to know when we generating information for the first component
5634 // associated with a capture, because the mapping flags depend on it.
5635 bool IsFirstComponentList = true;
5636
Samuel Antao86ace552016-04-27 22:40:57 +00005637 const ValueDecl *VD =
5638 Cap->capturesThis()
5639 ? nullptr
5640 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5641
Samuel Antao6890b092016-07-28 14:25:09 +00005642 // If this declaration appears in a is_device_ptr clause we just have to
5643 // pass the pointer by value. If it is a reference to a declaration, we just
5644 // pass its value, otherwise, if it is a member expression, we need to map
5645 // 'to' the field.
5646 if (!VD) {
5647 auto It = DevPointersMap.find(VD);
5648 if (It != DevPointersMap.end()) {
5649 for (auto L : It->second) {
5650 generateInfoForComponentList(
5651 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5652 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5653 IsFirstComponentList = false;
5654 }
5655 return;
5656 }
5657 } else if (DevPointersMap.count(VD)) {
5658 BasePointers.push_back({Arg, VD});
5659 Pointers.push_back(Arg);
5660 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5661 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5662 return;
5663 }
5664
Paul Robinson78fb1322016-08-01 22:12:46 +00005665 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005666 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00005667 for (auto L : C->decl_component_lists(VD)) {
5668 assert(L.first == VD &&
5669 "We got information for the wrong declaration??");
5670 assert(!L.second.empty() &&
5671 "Not expecting declaration with no component lists.");
5672 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5673 L.second, BasePointers, Pointers, Sizes,
5674 Types, IsFirstComponentList);
5675 IsFirstComponentList = false;
5676 }
5677
5678 return;
5679 }
Samuel Antaod486f842016-05-26 16:53:38 +00005680
5681 /// \brief Generate the default map information for a given capture \a CI,
5682 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00005683 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5684 const FieldDecl &RI, llvm::Value *CV,
5685 MapBaseValuesArrayTy &CurBasePointers,
5686 MapValuesArrayTy &CurPointers,
5687 MapValuesArrayTy &CurSizes,
5688 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00005689
5690 // Do the default mapping.
5691 if (CI.capturesThis()) {
5692 CurBasePointers.push_back(CV);
5693 CurPointers.push_back(CV);
5694 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5695 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5696 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00005697 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00005698 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005699 CurBasePointers.push_back(CV);
5700 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00005701 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005702 // We have to signal to the runtime captures passed by value that are
5703 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00005704 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00005705 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5706 } else {
5707 // Pointers are implicitly mapped with a zero size and no flags
5708 // (other than first map that is added for all implicit maps).
5709 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00005710 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5711 }
5712 } else {
5713 assert(CI.capturesVariable() && "Expected captured reference.");
5714 CurBasePointers.push_back(CV);
5715 CurPointers.push_back(CV);
5716
5717 const ReferenceType *PtrTy =
5718 cast<ReferenceType>(RI.getType().getTypePtr());
5719 QualType ElementType = PtrTy->getPointeeType();
5720 CurSizes.push_back(CGF.getTypeSize(ElementType));
5721 // The default map type for a scalar/complex type is 'to' because by
5722 // default the value doesn't have to be retrieved. For an aggregate
5723 // type, the default is 'tofrom'.
5724 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00005725 ? (OMP_MAP_TO | OMP_MAP_FROM)
5726 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00005727
5728 // If we have a capture by reference we may need to add the private
5729 // pointer flag if the base declaration shows in some first-private
5730 // clause.
5731 CurMapTypes.back() =
5732 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5733 }
5734 // Every default map produces a single argument, so, it is always the
5735 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00005736 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00005737 }
Samuel Antao86ace552016-04-27 22:40:57 +00005738};
Samuel Antaodf158d52016-04-27 22:58:19 +00005739
5740enum OpenMPOffloadingReservedDeviceIDs {
5741 /// \brief Device ID if the device was not defined, runtime should get it
5742 /// from environment variables in the spec.
5743 OMP_DEVICEID_UNDEF = -1,
5744};
5745} // anonymous namespace
5746
5747/// \brief Emit the arrays used to pass the captures and map information to the
5748/// offloading runtime library. If there is no map or capture information,
5749/// return nullptr by reference.
5750static void
Samuel Antaocc10b852016-07-28 14:23:26 +00005751emitOffloadingArrays(CodeGenFunction &CGF,
5752 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00005753 MappableExprsHandler::MapValuesArrayTy &Pointers,
5754 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00005755 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5756 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005757 auto &CGM = CGF.CGM;
5758 auto &Ctx = CGF.getContext();
5759
Samuel Antaocc10b852016-07-28 14:23:26 +00005760 // Reset the array information.
5761 Info.clearArrayInfo();
5762 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00005763
Samuel Antaocc10b852016-07-28 14:23:26 +00005764 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005765 // Detect if we have any capture size requiring runtime evaluation of the
5766 // size so that a constant array could be eventually used.
5767 bool hasRuntimeEvaluationCaptureSize = false;
5768 for (auto *S : Sizes)
5769 if (!isa<llvm::Constant>(S)) {
5770 hasRuntimeEvaluationCaptureSize = true;
5771 break;
5772 }
5773
Samuel Antaocc10b852016-07-28 14:23:26 +00005774 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00005775 QualType PointerArrayType =
5776 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5777 /*IndexTypeQuals=*/0);
5778
Samuel Antaocc10b852016-07-28 14:23:26 +00005779 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005780 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00005781 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005782 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5783
5784 // If we don't have any VLA types or other types that require runtime
5785 // evaluation, we can use a constant array for the map sizes, otherwise we
5786 // need to fill up the arrays as we do for the pointers.
5787 if (hasRuntimeEvaluationCaptureSize) {
5788 QualType SizeArrayType = Ctx.getConstantArrayType(
5789 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5790 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00005791 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005792 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5793 } else {
5794 // We expect all the sizes to be constant, so we collect them to create
5795 // a constant array.
5796 SmallVector<llvm::Constant *, 16> ConstSizes;
5797 for (auto S : Sizes)
5798 ConstSizes.push_back(cast<llvm::Constant>(S));
5799
5800 auto *SizesArrayInit = llvm::ConstantArray::get(
5801 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5802 auto *SizesArrayGbl = new llvm::GlobalVariable(
5803 CGM.getModule(), SizesArrayInit->getType(),
5804 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5805 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005806 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005807 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005808 }
5809
5810 // The map types are always constant so we don't need to generate code to
5811 // fill arrays. Instead, we create an array constant.
5812 llvm::Constant *MapTypesArrayInit =
5813 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5814 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5815 CGM.getModule(), MapTypesArrayInit->getType(),
5816 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5817 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005818 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005819 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005820
Samuel Antaocc10b852016-07-28 14:23:26 +00005821 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5822 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00005823 if (BPVal->getType()->isPointerTy())
5824 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5825 else {
5826 assert(BPVal->getType()->isIntegerTy() &&
5827 "If not a pointer, the value type must be an integer.");
5828 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5829 }
5830 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005831 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5832 Info.BasePointersArray, 0, i);
Samuel Antaodf158d52016-04-27 22:58:19 +00005833 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5834 CGF.Builder.CreateStore(BPVal, BPAddr);
5835
Samuel Antaocc10b852016-07-28 14:23:26 +00005836 if (Info.requiresDevicePointerInfo())
5837 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
5838 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
5839
Samuel Antaodf158d52016-04-27 22:58:19 +00005840 llvm::Value *PVal = Pointers[i];
5841 if (PVal->getType()->isPointerTy())
5842 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5843 else {
5844 assert(PVal->getType()->isIntegerTy() &&
5845 "If not a pointer, the value type must be an integer.");
5846 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5847 }
5848 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005849 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5850 Info.PointersArray, 0, i);
Samuel Antaodf158d52016-04-27 22:58:19 +00005851 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5852 CGF.Builder.CreateStore(PVal, PAddr);
5853
5854 if (hasRuntimeEvaluationCaptureSize) {
5855 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005856 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5857 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005858 /*Idx0=*/0,
5859 /*Idx1=*/i);
5860 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5861 CGF.Builder.CreateStore(
5862 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5863 SAddr);
5864 }
5865 }
5866 }
5867}
5868/// \brief Emit the arguments to be passed to the runtime library based on the
5869/// arrays of pointers, sizes and map types.
5870static void emitOffloadingArraysArgument(
5871 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5872 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005873 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005874 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00005875 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005876 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005877 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5878 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005879 /*Idx0=*/0, /*Idx1=*/0);
5880 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005881 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5882 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005883 /*Idx0=*/0,
5884 /*Idx1=*/0);
5885 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005886 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005887 /*Idx0=*/0, /*Idx1=*/0);
5888 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005889 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
5890 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005891 /*Idx0=*/0,
5892 /*Idx1=*/0);
5893 } else {
5894 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5895 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5896 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5897 MapTypesArrayArg =
5898 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
5899 }
Samuel Antao86ace552016-04-27 22:40:57 +00005900}
5901
Samuel Antaobed3c462015-10-02 16:14:20 +00005902void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
5903 const OMPExecutableDirective &D,
5904 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00005905 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00005906 const Expr *IfCond, const Expr *Device,
5907 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005908 if (!CGF.HaveInsertPoint())
5909 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00005910
Samuel Antaoee8fb302016-01-06 13:42:12 +00005911 assert(OutlinedFn && "Invalid outlined function!");
5912
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005913 auto &Ctx = CGF.getContext();
5914
Samuel Antao86ace552016-04-27 22:40:57 +00005915 // Fill up the arrays with all the captured variables.
5916 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00005917 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00005918 MappableExprsHandler::MapValuesArrayTy Pointers;
5919 MappableExprsHandler::MapValuesArrayTy Sizes;
5920 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00005921
Samuel Antaocc10b852016-07-28 14:23:26 +00005922 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00005923 MappableExprsHandler::MapValuesArrayTy CurPointers;
5924 MappableExprsHandler::MapValuesArrayTy CurSizes;
5925 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
5926
Samuel Antaod486f842016-05-26 16:53:38 +00005927 // Get mappable expression information.
5928 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005929
5930 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5931 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00005932 auto CV = CapturedVars.begin();
5933 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
5934 CE = CS.capture_end();
5935 CI != CE; ++CI, ++RI, ++CV) {
5936 StringRef Name;
5937 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00005938
Samuel Antao86ace552016-04-27 22:40:57 +00005939 CurBasePointers.clear();
5940 CurPointers.clear();
5941 CurSizes.clear();
5942 CurMapTypes.clear();
5943
5944 // VLA sizes are passed to the outlined region by copy and do not have map
5945 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00005946 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00005947 CurBasePointers.push_back(*CV);
5948 CurPointers.push_back(*CV);
5949 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005950 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00005951 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
5952 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005953 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00005954 // If we have any information in the map clause, we use it, otherwise we
5955 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00005956 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005957 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00005958 if (CurBasePointers.empty())
5959 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
5960 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00005961 }
Samuel Antao86ace552016-04-27 22:40:57 +00005962 // We expect to have at least an element of information for this capture.
5963 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
5964 assert(CurBasePointers.size() == CurPointers.size() &&
5965 CurBasePointers.size() == CurSizes.size() &&
5966 CurBasePointers.size() == CurMapTypes.size() &&
5967 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005968
Samuel Antao86ace552016-04-27 22:40:57 +00005969 // The kernel args are always the first elements of the base pointers
5970 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00005971 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00005972 // We need to append the results of this capture to what we already have.
5973 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
5974 Pointers.append(CurPointers.begin(), CurPointers.end());
5975 Sizes.append(CurSizes.begin(), CurSizes.end());
5976 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00005977 }
5978
5979 // Keep track on whether the host function has to be executed.
5980 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005981 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005982 auto OffloadError = CGF.MakeAddrLValue(
5983 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
5984 OffloadErrorQType);
5985 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
5986 OffloadError);
5987
5988 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antaodf158d52016-04-27 22:58:19 +00005989 auto &&ThenGen = [&Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
5990 OutlinedFnID, OffloadError, OffloadErrorQType,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005991 &D](CodeGenFunction &CGF, PrePostActionTy &) {
5992 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00005993 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00005994 TargetDataInfo Info;
5995 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
5996 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
5997 Info.PointersArray, Info.SizesArray,
5998 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00005999
6000 // On top of the arrays that were filled up, the target offloading call
6001 // takes as arguments the device id as well as the host pointer. The host
6002 // pointer is used by the runtime library to identify the current target
6003 // region, so it only has to be unique and not necessarily point to
6004 // anything. It could be the pointer to the outlined function that
6005 // implements the target region, but we aren't using that so that the
6006 // compiler doesn't need to keep that, and could therefore inline the host
6007 // function if proven worthwhile during optimization.
6008
Samuel Antaoee8fb302016-01-06 13:42:12 +00006009 // From this point on, we need to have an ID of the target region defined.
6010 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006011
6012 // Emit device ID if any.
6013 llvm::Value *DeviceID;
6014 if (Device)
6015 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006016 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006017 else
6018 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6019
Samuel Antaodf158d52016-04-27 22:58:19 +00006020 // Emit the number of elements in the offloading arrays.
6021 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6022
Samuel Antaob68e2db2016-03-03 16:20:23 +00006023 // Return value of the runtime offloading call.
6024 llvm::Value *Return;
6025
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006026 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
6027 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006028
6029 // If we have NumTeams defined this means that we have an enclosed teams
6030 // region. Therefore we also expect to have ThreadLimit defined. These two
6031 // values should be defined in the presence of a teams directive, regardless
6032 // of having any clauses associated. If the user is using teams but no
6033 // clauses, these two values will be the default that should be passed to
6034 // the runtime library - a 32-bit integer with the value zero.
6035 if (NumTeams) {
6036 assert(ThreadLimit && "Thread limit expression should be available along "
6037 "with number of teams.");
6038 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006039 DeviceID, OutlinedFnID,
6040 PointerNum, Info.BasePointersArray,
6041 Info.PointersArray, Info.SizesArray,
6042 Info.MapTypesArray, NumTeams,
6043 ThreadLimit};
Samuel Antaob68e2db2016-03-03 16:20:23 +00006044 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006045 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006046 } else {
6047 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006048 DeviceID, OutlinedFnID,
6049 PointerNum, Info.BasePointersArray,
6050 Info.PointersArray, Info.SizesArray,
6051 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006052 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00006053 OffloadingArgs);
6054 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006055
6056 CGF.EmitStoreOfScalar(Return, OffloadError);
6057 };
6058
Samuel Antaoee8fb302016-01-06 13:42:12 +00006059 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006060 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6061 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00006062 OffloadError);
6063 };
6064
6065 // If we have a target function ID it means that we need to support
6066 // offloading, otherwise, just execute on the host. We need to execute on host
6067 // regardless of the conditional in the if clause if, e.g., the user do not
6068 // specify target triples.
6069 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006070 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00006071 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006072 else {
6073 RegionCodeGenTy ThenRCG(ThenGen);
6074 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006075 }
6076 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006077 RegionCodeGenTy ElseRCG(ElseGen);
6078 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006079 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006080
6081 // Check the error code and execute the host version if required.
6082 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6083 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6084 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6085 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6086 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6087
6088 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00006089 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00006090 CGF.EmitBranch(OffloadContBlock);
6091
6092 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006093}
Samuel Antaoee8fb302016-01-06 13:42:12 +00006094
6095void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6096 StringRef ParentName) {
6097 if (!S)
6098 return;
6099
6100 // If we find a OMP target directive, codegen the outline function and
6101 // register the result.
6102 // FIXME: Add other directives with target when they become supported.
6103 bool isTargetDirective = isa<OMPTargetDirective>(S);
6104
6105 if (isTargetDirective) {
6106 auto *E = cast<OMPExecutableDirective>(S);
6107 unsigned DeviceID;
6108 unsigned FileID;
6109 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006110 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006111 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006112
6113 // Is this a target region that should not be emitted as an entry point? If
6114 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00006115 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6116 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00006117 return;
6118
6119 llvm::Function *Fn;
6120 llvm::Constant *Addr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006121 std::tie(Fn, Addr) =
6122 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
6123 CGM, cast<OMPTargetDirective>(*E), ParentName,
6124 /*isOffloadEntry=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006125 assert(Fn && Addr && "Target region emission failed.");
6126 return;
6127 }
6128
6129 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00006130 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00006131 return;
6132
6133 scanForTargetRegionsFunctions(
6134 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6135 ParentName);
6136 return;
6137 }
6138
6139 // If this is a lambda function, look into its body.
6140 if (auto *L = dyn_cast<LambdaExpr>(S))
6141 S = L->getBody();
6142
6143 // Keep looking for target regions recursively.
6144 for (auto *II : S->children())
6145 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006146}
6147
6148bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6149 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6150
6151 // If emitting code for the host, we do not process FD here. Instead we do
6152 // the normal code generation.
6153 if (!CGM.getLangOpts().OpenMPIsDevice)
6154 return false;
6155
6156 // Try to detect target regions in the function.
6157 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6158
Samuel Antao4b75b872016-12-12 19:26:31 +00006159 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00006160 // scanning. Therefore, we signal that this function is completely dealt
6161 // with.
6162 return true;
6163}
6164
6165bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6166 if (!CGM.getLangOpts().OpenMPIsDevice)
6167 return false;
6168
6169 // Check if there are Ctors/Dtors in this declaration and look for target
6170 // regions in it. We use the complete variant to produce the kernel name
6171 // mangling.
6172 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6173 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6174 for (auto *Ctor : RD->ctors()) {
6175 StringRef ParentName =
6176 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6177 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6178 }
6179 auto *Dtor = RD->getDestructor();
6180 if (Dtor) {
6181 StringRef ParentName =
6182 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6183 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6184 }
6185 }
6186
6187 // If we are in target mode we do not emit any global (declare target is not
6188 // implemented yet). Therefore we signal that GD was processed in this case.
6189 return true;
6190}
6191
6192bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6193 auto *VD = GD.getDecl();
6194 if (isa<FunctionDecl>(VD))
6195 return emitTargetFunctions(GD);
6196
6197 return emitTargetGlobalVariable(GD);
6198}
6199
6200llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6201 // If we have offloading in the current module, we need to emit the entries
6202 // now and register the offloading descriptor.
6203 createOffloadEntriesAndInfoMetadata();
6204
6205 // Create and register the offloading binary descriptors. This is the main
6206 // entity that captures all the information about offloading in the current
6207 // compilation unit.
6208 return createOffloadingBinaryDescriptorRegistration();
6209}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006210
6211void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6212 const OMPExecutableDirective &D,
6213 SourceLocation Loc,
6214 llvm::Value *OutlinedFn,
6215 ArrayRef<llvm::Value *> CapturedVars) {
6216 if (!CGF.HaveInsertPoint())
6217 return;
6218
6219 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6220 CodeGenFunction::RunCleanupsScope Scope(CGF);
6221
6222 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6223 llvm::Value *Args[] = {
6224 RTLoc,
6225 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6226 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6227 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6228 RealArgs.append(std::begin(Args), std::end(Args));
6229 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6230
6231 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6232 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6233}
6234
6235void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00006236 const Expr *NumTeams,
6237 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006238 SourceLocation Loc) {
6239 if (!CGF.HaveInsertPoint())
6240 return;
6241
6242 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6243
Carlo Bertollic6872252016-04-04 15:55:02 +00006244 llvm::Value *NumTeamsVal =
6245 (NumTeams)
6246 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6247 CGF.CGM.Int32Ty, /* isSigned = */ true)
6248 : CGF.Builder.getInt32(0);
6249
6250 llvm::Value *ThreadLimitVal =
6251 (ThreadLimit)
6252 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6253 CGF.CGM.Int32Ty, /* isSigned = */ true)
6254 : CGF.Builder.getInt32(0);
6255
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006256 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00006257 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6258 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006259 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6260 PushNumTeamsArgs);
6261}
Samuel Antaodf158d52016-04-27 22:58:19 +00006262
Samuel Antaocc10b852016-07-28 14:23:26 +00006263void CGOpenMPRuntime::emitTargetDataCalls(
6264 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6265 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006266 if (!CGF.HaveInsertPoint())
6267 return;
6268
Samuel Antaocc10b852016-07-28 14:23:26 +00006269 // Action used to replace the default codegen action and turn privatization
6270 // off.
6271 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00006272
6273 // Generate the code for the opening of the data environment. Capture all the
6274 // arguments of the runtime call by reference because they are used in the
6275 // closing of the region.
Samuel Antaocc10b852016-07-28 14:23:26 +00006276 auto &&BeginThenGen = [&D, &CGF, Device, &Info, &CodeGen, &NoPrivAction](
6277 CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006278 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006279 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00006280 MappableExprsHandler::MapValuesArrayTy Pointers;
6281 MappableExprsHandler::MapValuesArrayTy Sizes;
6282 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6283
6284 // Get map clause information.
6285 MappableExprsHandler MCHandler(D, CGF);
6286 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00006287
6288 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006289 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006290
6291 llvm::Value *BasePointersArrayArg = nullptr;
6292 llvm::Value *PointersArrayArg = nullptr;
6293 llvm::Value *SizesArrayArg = nullptr;
6294 llvm::Value *MapTypesArrayArg = nullptr;
6295 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006296 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006297
6298 // Emit device ID if any.
6299 llvm::Value *DeviceID = nullptr;
6300 if (Device)
6301 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6302 CGF.Int32Ty, /*isSigned=*/true);
6303 else
6304 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6305
6306 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006307 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006308
6309 llvm::Value *OffloadingArgs[] = {
6310 DeviceID, PointerNum, BasePointersArrayArg,
6311 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6312 auto &RT = CGF.CGM.getOpenMPRuntime();
6313 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6314 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00006315
6316 // If device pointer privatization is required, emit the body of the region
6317 // here. It will have to be duplicated: with and without privatization.
6318 if (!Info.CaptureDeviceAddrMap.empty())
6319 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006320 };
6321
6322 // Generate code for the closing of the data region.
Samuel Antaocc10b852016-07-28 14:23:26 +00006323 auto &&EndThenGen = [&CGF, Device, &Info](CodeGenFunction &CGF,
6324 PrePostActionTy &) {
6325 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00006326
6327 llvm::Value *BasePointersArrayArg = nullptr;
6328 llvm::Value *PointersArrayArg = nullptr;
6329 llvm::Value *SizesArrayArg = nullptr;
6330 llvm::Value *MapTypesArrayArg = nullptr;
6331 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006332 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006333
6334 // Emit device ID if any.
6335 llvm::Value *DeviceID = nullptr;
6336 if (Device)
6337 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6338 CGF.Int32Ty, /*isSigned=*/true);
6339 else
6340 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6341
6342 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006343 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006344
6345 llvm::Value *OffloadingArgs[] = {
6346 DeviceID, PointerNum, BasePointersArrayArg,
6347 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6348 auto &RT = CGF.CGM.getOpenMPRuntime();
6349 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6350 OffloadingArgs);
6351 };
6352
Samuel Antaocc10b852016-07-28 14:23:26 +00006353 // If we need device pointer privatization, we need to emit the body of the
6354 // region with no privatization in the 'else' branch of the conditional.
6355 // Otherwise, we don't have to do anything.
6356 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6357 PrePostActionTy &) {
6358 if (!Info.CaptureDeviceAddrMap.empty()) {
6359 CodeGen.setAction(NoPrivAction);
6360 CodeGen(CGF);
6361 }
6362 };
6363
6364 // We don't have to do anything to close the region if the if clause evaluates
6365 // to false.
6366 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00006367
6368 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006369 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006370 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006371 RegionCodeGenTy RCG(BeginThenGen);
6372 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006373 }
6374
Samuel Antaocc10b852016-07-28 14:23:26 +00006375 // If we don't require privatization of device pointers, we emit the body in
6376 // between the runtime calls. This avoids duplicating the body code.
6377 if (Info.CaptureDeviceAddrMap.empty()) {
6378 CodeGen.setAction(NoPrivAction);
6379 CodeGen(CGF);
6380 }
Samuel Antaodf158d52016-04-27 22:58:19 +00006381
6382 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006383 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006384 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006385 RegionCodeGenTy RCG(EndThenGen);
6386 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006387 }
6388}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006389
Samuel Antao8d2d7302016-05-26 18:30:22 +00006390void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00006391 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6392 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006393 if (!CGF.HaveInsertPoint())
6394 return;
6395
Samuel Antao8dd66282016-04-27 23:14:30 +00006396 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00006397 isa<OMPTargetExitDataDirective>(D) ||
6398 isa<OMPTargetUpdateDirective>(D)) &&
6399 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00006400
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006401 // Generate the code for the opening of the data environment.
6402 auto &&ThenGen = [&D, &CGF, Device](CodeGenFunction &CGF, PrePostActionTy &) {
6403 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006404 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006405 MappableExprsHandler::MapValuesArrayTy Pointers;
6406 MappableExprsHandler::MapValuesArrayTy Sizes;
6407 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6408
6409 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00006410 MappableExprsHandler MEHandler(D, CGF);
6411 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006412
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006413 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006414 TargetDataInfo Info;
6415 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6416 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6417 Info.PointersArray, Info.SizesArray,
6418 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006419
6420 // Emit device ID if any.
6421 llvm::Value *DeviceID = nullptr;
6422 if (Device)
6423 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6424 CGF.Int32Ty, /*isSigned=*/true);
6425 else
6426 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6427
6428 // Emit the number of elements in the offloading arrays.
6429 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6430
6431 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006432 DeviceID, PointerNum, Info.BasePointersArray,
6433 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00006434
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006435 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00006436 // Select the right runtime function call for each expected standalone
6437 // directive.
6438 OpenMPRTLFunction RTLFn;
6439 switch (D.getDirectiveKind()) {
6440 default:
6441 llvm_unreachable("Unexpected standalone target data directive.");
6442 break;
6443 case OMPD_target_enter_data:
6444 RTLFn = OMPRTL__tgt_target_data_begin;
6445 break;
6446 case OMPD_target_exit_data:
6447 RTLFn = OMPRTL__tgt_target_data_end;
6448 break;
6449 case OMPD_target_update:
6450 RTLFn = OMPRTL__tgt_target_data_update;
6451 break;
6452 }
6453 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006454 };
6455
6456 // In the event we get an if clause, we don't have to take any action on the
6457 // else side.
6458 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6459
6460 if (IfCond) {
6461 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6462 } else {
6463 RegionCodeGenTy ThenGenRCG(ThenGen);
6464 ThenGenRCG(CGF);
6465 }
6466}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006467
6468namespace {
6469 /// Kind of parameter in a function with 'declare simd' directive.
6470 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6471 /// Attribute set of the parameter.
6472 struct ParamAttrTy {
6473 ParamKindTy Kind = Vector;
6474 llvm::APSInt StrideOrArg;
6475 llvm::APSInt Alignment;
6476 };
6477} // namespace
6478
6479static unsigned evaluateCDTSize(const FunctionDecl *FD,
6480 ArrayRef<ParamAttrTy> ParamAttrs) {
6481 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6482 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6483 // of that clause. The VLEN value must be power of 2.
6484 // In other case the notion of the function`s "characteristic data type" (CDT)
6485 // is used to compute the vector length.
6486 // CDT is defined in the following order:
6487 // a) For non-void function, the CDT is the return type.
6488 // b) If the function has any non-uniform, non-linear parameters, then the
6489 // CDT is the type of the first such parameter.
6490 // c) If the CDT determined by a) or b) above is struct, union, or class
6491 // type which is pass-by-value (except for the type that maps to the
6492 // built-in complex data type), the characteristic data type is int.
6493 // d) If none of the above three cases is applicable, the CDT is int.
6494 // The VLEN is then determined based on the CDT and the size of vector
6495 // register of that ISA for which current vector version is generated. The
6496 // VLEN is computed using the formula below:
6497 // VLEN = sizeof(vector_register) / sizeof(CDT),
6498 // where vector register size specified in section 3.2.1 Registers and the
6499 // Stack Frame of original AMD64 ABI document.
6500 QualType RetType = FD->getReturnType();
6501 if (RetType.isNull())
6502 return 0;
6503 ASTContext &C = FD->getASTContext();
6504 QualType CDT;
6505 if (!RetType.isNull() && !RetType->isVoidType())
6506 CDT = RetType;
6507 else {
6508 unsigned Offset = 0;
6509 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6510 if (ParamAttrs[Offset].Kind == Vector)
6511 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6512 ++Offset;
6513 }
6514 if (CDT.isNull()) {
6515 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6516 if (ParamAttrs[I + Offset].Kind == Vector) {
6517 CDT = FD->getParamDecl(I)->getType();
6518 break;
6519 }
6520 }
6521 }
6522 }
6523 if (CDT.isNull())
6524 CDT = C.IntTy;
6525 CDT = CDT->getCanonicalTypeUnqualified();
6526 if (CDT->isRecordType() || CDT->isUnionType())
6527 CDT = C.IntTy;
6528 return C.getTypeSize(CDT);
6529}
6530
6531static void
6532emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00006533 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006534 ArrayRef<ParamAttrTy> ParamAttrs,
6535 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6536 struct ISADataTy {
6537 char ISA;
6538 unsigned VecRegSize;
6539 };
6540 ISADataTy ISAData[] = {
6541 {
6542 'b', 128
6543 }, // SSE
6544 {
6545 'c', 256
6546 }, // AVX
6547 {
6548 'd', 256
6549 }, // AVX2
6550 {
6551 'e', 512
6552 }, // AVX512
6553 };
6554 llvm::SmallVector<char, 2> Masked;
6555 switch (State) {
6556 case OMPDeclareSimdDeclAttr::BS_Undefined:
6557 Masked.push_back('N');
6558 Masked.push_back('M');
6559 break;
6560 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6561 Masked.push_back('N');
6562 break;
6563 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6564 Masked.push_back('M');
6565 break;
6566 }
6567 for (auto Mask : Masked) {
6568 for (auto &Data : ISAData) {
6569 SmallString<256> Buffer;
6570 llvm::raw_svector_ostream Out(Buffer);
6571 Out << "_ZGV" << Data.ISA << Mask;
6572 if (!VLENVal) {
6573 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6574 evaluateCDTSize(FD, ParamAttrs));
6575 } else
6576 Out << VLENVal;
6577 for (auto &ParamAttr : ParamAttrs) {
6578 switch (ParamAttr.Kind){
6579 case LinearWithVarStride:
6580 Out << 's' << ParamAttr.StrideOrArg;
6581 break;
6582 case Linear:
6583 Out << 'l';
6584 if (!!ParamAttr.StrideOrArg)
6585 Out << ParamAttr.StrideOrArg;
6586 break;
6587 case Uniform:
6588 Out << 'u';
6589 break;
6590 case Vector:
6591 Out << 'v';
6592 break;
6593 }
6594 if (!!ParamAttr.Alignment)
6595 Out << 'a' << ParamAttr.Alignment;
6596 }
6597 Out << '_' << Fn->getName();
6598 Fn->addFnAttr(Out.str());
6599 }
6600 }
6601}
6602
6603void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6604 llvm::Function *Fn) {
6605 ASTContext &C = CGM.getContext();
6606 FD = FD->getCanonicalDecl();
6607 // Map params to their positions in function decl.
6608 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6609 if (isa<CXXMethodDecl>(FD))
6610 ParamPositions.insert({FD, 0});
6611 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00006612 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006613 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6614 ++ParamPos;
6615 }
6616 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6617 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6618 // Mark uniform parameters.
6619 for (auto *E : Attr->uniforms()) {
6620 E = E->IgnoreParenImpCasts();
6621 unsigned Pos;
6622 if (isa<CXXThisExpr>(E))
6623 Pos = ParamPositions[FD];
6624 else {
6625 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6626 ->getCanonicalDecl();
6627 Pos = ParamPositions[PVD];
6628 }
6629 ParamAttrs[Pos].Kind = Uniform;
6630 }
6631 // Get alignment info.
6632 auto NI = Attr->alignments_begin();
6633 for (auto *E : Attr->aligneds()) {
6634 E = E->IgnoreParenImpCasts();
6635 unsigned Pos;
6636 QualType ParmTy;
6637 if (isa<CXXThisExpr>(E)) {
6638 Pos = ParamPositions[FD];
6639 ParmTy = E->getType();
6640 } else {
6641 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6642 ->getCanonicalDecl();
6643 Pos = ParamPositions[PVD];
6644 ParmTy = PVD->getType();
6645 }
6646 ParamAttrs[Pos].Alignment =
6647 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6648 : llvm::APSInt::getUnsigned(
6649 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6650 .getQuantity());
6651 ++NI;
6652 }
6653 // Mark linear parameters.
6654 auto SI = Attr->steps_begin();
6655 auto MI = Attr->modifiers_begin();
6656 for (auto *E : Attr->linears()) {
6657 E = E->IgnoreParenImpCasts();
6658 unsigned Pos;
6659 if (isa<CXXThisExpr>(E))
6660 Pos = ParamPositions[FD];
6661 else {
6662 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6663 ->getCanonicalDecl();
6664 Pos = ParamPositions[PVD];
6665 }
6666 auto &ParamAttr = ParamAttrs[Pos];
6667 ParamAttr.Kind = Linear;
6668 if (*SI) {
6669 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6670 Expr::SE_AllowSideEffects)) {
6671 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6672 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6673 ParamAttr.Kind = LinearWithVarStride;
6674 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6675 ParamPositions[StridePVD->getCanonicalDecl()]);
6676 }
6677 }
6678 }
6679 }
6680 ++SI;
6681 ++MI;
6682 }
6683 llvm::APSInt VLENVal;
6684 if (const Expr *VLEN = Attr->getSimdlen())
6685 VLENVal = VLEN->EvaluateKnownConstInt(C);
6686 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6687 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6688 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6689 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6690 }
6691}
Alexey Bataev8b427062016-05-25 12:36:08 +00006692
6693namespace {
6694/// Cleanup action for doacross support.
6695class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6696public:
6697 static const int DoacrossFinArgs = 2;
6698
6699private:
6700 llvm::Value *RTLFn;
6701 llvm::Value *Args[DoacrossFinArgs];
6702
6703public:
6704 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6705 : RTLFn(RTLFn) {
6706 assert(CallArgs.size() == DoacrossFinArgs);
6707 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6708 }
6709 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6710 if (!CGF.HaveInsertPoint())
6711 return;
6712 CGF.EmitRuntimeCall(RTLFn, Args);
6713 }
6714};
6715} // namespace
6716
6717void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6718 const OMPLoopDirective &D) {
6719 if (!CGF.HaveInsertPoint())
6720 return;
6721
6722 ASTContext &C = CGM.getContext();
6723 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6724 RecordDecl *RD;
6725 if (KmpDimTy.isNull()) {
6726 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6727 // kmp_int64 lo; // lower
6728 // kmp_int64 up; // upper
6729 // kmp_int64 st; // stride
6730 // };
6731 RD = C.buildImplicitRecord("kmp_dim");
6732 RD->startDefinition();
6733 addFieldToRecordDecl(C, RD, Int64Ty);
6734 addFieldToRecordDecl(C, RD, Int64Ty);
6735 addFieldToRecordDecl(C, RD, Int64Ty);
6736 RD->completeDefinition();
6737 KmpDimTy = C.getRecordType(RD);
6738 } else
6739 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6740
6741 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6742 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6743 enum { LowerFD = 0, UpperFD, StrideFD };
6744 // Fill dims with data.
6745 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6746 // dims.upper = num_iterations;
6747 LValue UpperLVal =
6748 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6749 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6750 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6751 Int64Ty, D.getNumIterations()->getExprLoc());
6752 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6753 // dims.stride = 1;
6754 LValue StrideLVal =
6755 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6756 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6757 StrideLVal);
6758
6759 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6760 // kmp_int32 num_dims, struct kmp_dim * dims);
6761 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6762 getThreadID(CGF, D.getLocStart()),
6763 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6764 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6765 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6766
6767 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6768 CGF.EmitRuntimeCall(RTLFn, Args);
6769 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6770 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6771 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6772 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6773 llvm::makeArrayRef(FiniArgs));
6774}
6775
6776void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6777 const OMPDependClause *C) {
6778 QualType Int64Ty =
6779 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6780 const Expr *CounterVal = C->getCounterValue();
6781 assert(CounterVal);
6782 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6783 CounterVal->getType(), Int64Ty,
6784 CounterVal->getExprLoc());
6785 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6786 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6787 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6788 getThreadID(CGF, C->getLocStart()),
6789 CntAddr.getPointer()};
6790 llvm::Value *RTLFn;
6791 if (C->getDependencyKind() == OMPC_DEPEND_source)
6792 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6793 else {
6794 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6795 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6796 }
6797 CGF.EmitRuntimeCall(RTLFn, Args);
6798}
6799