blob: 61e2f74c6077ba78813cee42d92e83d2c1faf94b [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"
18#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "llvm/ADT/ArrayRef.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000021#include "llvm/Bitcode/ReaderWriter.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000026#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000027#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000028#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000029
30using namespace clang;
31using namespace CodeGen;
32
Benjamin Kramerc52193f2014-10-10 13:57:57 +000033namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000034/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000035class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
36public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000037 /// \brief Kinds of OpenMP regions used in codegen.
38 enum CGOpenMPRegionKind {
39 /// \brief Region with outlined function for standalone 'parallel'
40 /// directive.
41 ParallelOutlinedRegion,
42 /// \brief Region with outlined function for standalone 'task' directive.
43 TaskOutlinedRegion,
44 /// \brief Region for constructs that do not require function outlining,
45 /// like 'for', 'sections', 'atomic' etc. directives.
46 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000047 /// \brief Region with outlined function for standalone 'target' directive.
48 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000049 };
Alexey Bataev18095712014-10-10 12:19:54 +000050
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 CGOpenMPRegionInfo(const CapturedStmt &CS,
52 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000053 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
54 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000055 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057
58 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
60 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000061 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000063
64 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000065 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000069 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000071 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000072 /// \return LValue for thread id variable. This LValue always has type int32*.
73 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000074
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000076
Alexey Bataev81c7ea02015-07-03 09:56:58 +000077 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
78
Alexey Bataev25e5b442015-09-15 12:52:43 +000079 bool hasCancel() const { return HasCancel; }
80
Alexey Bataev18095712014-10-10 12:19:54 +000081 static bool classof(const CGCapturedStmtInfo *Info) {
82 return Info->getKind() == CR_OpenMP;
83 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000084
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000085protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000086 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000087 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000088 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000089 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090};
Alexey Bataev18095712014-10-10 12:19:54 +000091
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092/// \brief API for captured statement code generation in OpenMP constructs.
93class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
94public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +000096 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +000097 OpenMPDirectiveKind Kind, bool HasCancel)
98 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
99 HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
102 }
103 /// \brief Get a variable or parameter for storing global thread id
104 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000105 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000106
Alexey Bataev18095712014-10-10 12:19:54 +0000107 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000108 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +0000109
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000110 static bool classof(const CGCapturedStmtInfo *Info) {
111 return CGOpenMPRegionInfo::classof(Info) &&
112 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
113 ParallelOutlinedRegion;
114 }
115
Alexey Bataev18095712014-10-10 12:19:54 +0000116private:
117 /// \brief A variable or parameter storing global thread id for OpenMP
118 /// constructs.
119 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000120};
121
Alexey Bataev62b63b12015-03-10 07:28:44 +0000122/// \brief API for captured statement code generation in OpenMP constructs.
123class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
124public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000125 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000126 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000127 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000128 OpenMPDirectiveKind Kind, bool HasCancel)
129 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000130 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000131 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
132 }
133 /// \brief Get a variable or parameter for storing global thread id
134 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000135 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000136
137 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000138 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000139
Alexey Bataev62b63b12015-03-10 07:28:44 +0000140 /// \brief Get the name of the capture helper.
141 StringRef getHelperName() const override { return ".omp_outlined."; }
142
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000143 static bool classof(const CGCapturedStmtInfo *Info) {
144 return CGOpenMPRegionInfo::classof(Info) &&
145 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
146 TaskOutlinedRegion;
147 }
148
Alexey Bataev62b63b12015-03-10 07:28:44 +0000149private:
150 /// \brief A variable or parameter storing global thread id for OpenMP
151 /// constructs.
152 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000153};
154
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000155/// \brief API for inlined captured statement code generation in OpenMP
156/// constructs.
157class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
158public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000159 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000160 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000161 OpenMPDirectiveKind Kind, bool HasCancel)
162 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
163 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000164 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
165 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000166 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000167 if (OuterRegionInfo)
168 return OuterRegionInfo->getContextValue();
169 llvm_unreachable("No context value for inlined OpenMP region");
170 }
Hans Wennborg7eb54642015-09-10 17:07:54 +0000171 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000172 if (OuterRegionInfo) {
173 OuterRegionInfo->setContextValue(V);
174 return;
175 }
176 llvm_unreachable("No context value for inlined OpenMP region");
177 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000178 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000179 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000180 if (OuterRegionInfo)
181 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000182 // If there is no outer outlined region,no need to lookup in a list of
183 // captured variables, we can use the original one.
184 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000185 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000186 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000187 if (OuterRegionInfo)
188 return OuterRegionInfo->getThisFieldDecl();
189 return nullptr;
190 }
191 /// \brief Get a variable or parameter for storing global thread id
192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000194 if (OuterRegionInfo)
195 return OuterRegionInfo->getThreadIDVariable();
196 return nullptr;
197 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000199 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000200 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000201 if (auto *OuterRegionInfo = getOldCSI())
202 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000203 llvm_unreachable("No helper name for inlined OpenMP construct");
204 }
205
206 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
207
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000208 static bool classof(const CGCapturedStmtInfo *Info) {
209 return CGOpenMPRegionInfo::classof(Info) &&
210 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
211 }
212
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000213private:
214 /// \brief CodeGen info about outer OpenMP region.
215 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
216 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000217};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000218
Samuel Antaobed3c462015-10-02 16:14:20 +0000219/// \brief API for captured statement code generation in OpenMP target
220/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000221/// captured fields. The name of the target region has to be unique in a given
222/// application so it is provided by the client, because only the client has
223/// the information to generate that.
Samuel Antaobed3c462015-10-02 16:14:20 +0000224class CGOpenMPTargetRegionInfo : public CGOpenMPRegionInfo {
225public:
226 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000227 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000228 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000229 /*HasCancel=*/false),
230 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000231
232 /// \brief This is unused for target regions because each starts executing
233 /// with a single thread.
234 const VarDecl *getThreadIDVariable() const override { return nullptr; }
235
236 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000237 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000238
239 static bool classof(const CGCapturedStmtInfo *Info) {
240 return CGOpenMPRegionInfo::classof(Info) &&
241 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
242 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000243
244private:
245 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000246};
247
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000248/// \brief RAII for emitting code of OpenMP constructs.
249class InlinedOpenMPRegionRAII {
250 CodeGenFunction &CGF;
251
252public:
253 /// \brief Constructs region for combined constructs.
254 /// \param CodeGen Code generation sequence for combined directives. Includes
255 /// a list of functions used for code generation of implicitly inlined
256 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000257 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000258 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000259 : CGF(CGF) {
260 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000261 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
262 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000263 }
264 ~InlinedOpenMPRegionRAII() {
265 // Restore original CapturedStmtInfo only if we're done with code emission.
266 auto *OldCSI =
267 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
268 delete CGF.CapturedStmtInfo;
269 CGF.CapturedStmtInfo = OldCSI;
270 }
271};
272
Hans Wennborg7eb54642015-09-10 17:07:54 +0000273} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000274
275LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000276 return CGF.EmitLoadOfPointerLValue(
277 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
278 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000279}
280
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000281void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000282 if (!CGF.HaveInsertPoint())
283 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000284 // 1.2.2 OpenMP Language Terminology
285 // Structured block - An executable statement with a single entry at the
286 // top and a single exit at the bottom.
287 // The point of exit cannot be a branch out of the structured block.
288 // longjmp() and throw() must not violate the entry/exit criteria.
289 CGF.EHStack.pushTerminate();
290 {
291 CodeGenFunction::RunCleanupsScope Scope(CGF);
292 CodeGen(CGF);
293 }
294 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000295}
296
Alexey Bataev62b63b12015-03-10 07:28:44 +0000297LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
298 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000299 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
300 getThreadIDVariable()->getType(),
301 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000302}
303
Alexey Bataev9959db52014-05-06 10:08:46 +0000304CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Samuel Antaoee8fb302016-01-06 13:42:12 +0000305 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr),
306 OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000307 IdentTy = llvm::StructType::create(
308 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
309 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000310 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000311 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000312 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
313 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000314 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000315 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000316
317 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000318}
319
Alexey Bataev91797552015-03-18 04:13:55 +0000320void CGOpenMPRuntime::clear() {
321 InternalVars.clear();
322}
323
John McCall7f416cc2015-09-08 08:05:57 +0000324// Layout information for ident_t.
325static CharUnits getIdentAlign(CodeGenModule &CGM) {
326 return CGM.getPointerAlign();
327}
328static CharUnits getIdentSize(CodeGenModule &CGM) {
329 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
330 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
331}
332static CharUnits getOffsetOfIdentField(CGOpenMPRuntime::IdentFieldIndex Field) {
333 // All the fields except the last are i32, so this works beautifully.
334 return unsigned(Field) * CharUnits::fromQuantity(4);
335}
336static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
337 CGOpenMPRuntime::IdentFieldIndex Field,
338 const llvm::Twine &Name = "") {
339 auto Offset = getOffsetOfIdentField(Field);
340 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
341}
342
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000343llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
344 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
345 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000346 assert(ThreadIDVar->getType()->isPointerType() &&
347 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000348 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
349 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000350 bool HasCancel = false;
351 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
352 HasCancel = OPD->hasCancel();
353 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
354 HasCancel = OPSD->hasCancel();
355 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
356 HasCancel = OPFD->hasCancel();
357 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
358 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000359 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000360 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000361}
362
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000363llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
364 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
365 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000366 assert(!ThreadIDVar->getType()->isPointerType() &&
367 "thread id variable must be of type kmp_int32 for tasks");
368 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
369 CodeGenFunction CGF(CGM, true);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000370 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000371 InnermostKind,
372 cast<OMPTaskDirective>(D).hasCancel());
Alexey Bataevd157d472015-06-24 03:35:38 +0000373 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000374 return CGF.GenerateCapturedStmtFunction(*CS);
375}
376
John McCall7f416cc2015-09-08 08:05:57 +0000377Address CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
378 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000379 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000380 if (!Entry) {
381 if (!DefaultOpenMPPSource) {
382 // Initialize default location for psource field of ident_t structure of
383 // all ident_t objects. Format is ";file;function;line;column;;".
384 // Taken from
385 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
386 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000387 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000388 DefaultOpenMPPSource =
389 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
390 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000391 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
392 CGM.getModule(), IdentTy, /*isConstant*/ true,
393 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000394 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000395 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000396
397 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000398 llvm::Constant *Values[] = {Zero,
399 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
400 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000401 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
402 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000403 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000404 }
John McCall7f416cc2015-09-08 08:05:57 +0000405 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000406}
407
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000408llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
409 SourceLocation Loc,
410 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000411 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000412 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000413 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000414 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000415
416 assert(CGF.CurFn && "No function in current CodeGenFunction.");
417
John McCall7f416cc2015-09-08 08:05:57 +0000418 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000419 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
420 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000421 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
422
Alexander Musmanc6388682014-12-15 07:07:06 +0000423 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
424 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000425 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000426 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000427 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
428 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000429 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000430 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000431 LocValue = AI;
432
433 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
434 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000435 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000436 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000437 }
438
439 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000440 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000441
Alexey Bataevf002aca2014-05-30 05:48:40 +0000442 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
443 if (OMPDebugLoc == nullptr) {
444 SmallString<128> Buffer2;
445 llvm::raw_svector_ostream OS2(Buffer2);
446 // Build debug location
447 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
448 OS2 << ";" << PLoc.getFilename() << ";";
449 if (const FunctionDecl *FD =
450 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
451 OS2 << FD->getQualifiedNameAsString();
452 }
453 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
454 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
455 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000456 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000457 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000458 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
459
John McCall7f416cc2015-09-08 08:05:57 +0000460 // Our callers always pass this to a runtime function, so for
461 // convenience, go ahead and return a naked pointer.
462 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000463}
464
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000465llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
466 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000467 assert(CGF.CurFn && "No function in current CodeGenFunction.");
468
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000469 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000470 // Check whether we've already cached a load of the thread id in this
471 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000472 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000473 if (I != OpenMPLocThreadIDMap.end()) {
474 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000475 if (ThreadID != nullptr)
476 return ThreadID;
477 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000478 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000479 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000480 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000481 // Check if this an outlined function with thread id passed as argument.
482 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000483 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
484 // If value loaded in entry block, cache it and use it everywhere in
485 // function.
486 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
487 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
488 Elem.second.ThreadID = ThreadID;
489 }
490 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000491 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000492 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000493
494 // This is not an outlined function region - need to call __kmpc_int32
495 // kmpc_global_thread_num(ident_t *loc).
496 // Generate thread id value and cache this value for use across the
497 // function.
498 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
499 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
500 ThreadID =
501 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
502 emitUpdateLocation(CGF, Loc));
503 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
504 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000505 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000506}
507
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000508void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000509 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000510 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
511 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000512}
513
514llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
515 return llvm::PointerType::getUnqual(IdentTy);
516}
517
518llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
519 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
520}
521
522llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000523CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000524 llvm::Constant *RTLFn = nullptr;
525 switch (Function) {
526 case OMPRTL__kmpc_fork_call: {
527 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
528 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000529 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
530 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000531 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000532 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000533 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
534 break;
535 }
536 case OMPRTL__kmpc_global_thread_num: {
537 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000538 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000539 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000540 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000541 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
542 break;
543 }
Alexey Bataev97720002014-11-11 04:05:39 +0000544 case OMPRTL__kmpc_threadprivate_cached: {
545 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
546 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
547 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
548 CGM.VoidPtrTy, CGM.SizeTy,
549 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
550 llvm::FunctionType *FnTy =
551 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
552 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
553 break;
554 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000555 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000556 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
557 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000558 llvm::Type *TypeParams[] = {
559 getIdentTyPointerTy(), CGM.Int32Ty,
560 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
561 llvm::FunctionType *FnTy =
562 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
563 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
564 break;
565 }
Alexey Bataevfc57d162015-12-15 10:55:09 +0000566 case OMPRTL__kmpc_critical_with_hint: {
567 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
568 // kmp_critical_name *crit, uintptr_t hint);
569 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
570 llvm::PointerType::getUnqual(KmpCriticalNameTy),
571 CGM.IntPtrTy};
572 llvm::FunctionType *FnTy =
573 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
575 break;
576 }
Alexey Bataev97720002014-11-11 04:05:39 +0000577 case OMPRTL__kmpc_threadprivate_register: {
578 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
579 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
580 // typedef void *(*kmpc_ctor)(void *);
581 auto KmpcCtorTy =
582 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
583 /*isVarArg*/ false)->getPointerTo();
584 // typedef void *(*kmpc_cctor)(void *, void *);
585 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
586 auto KmpcCopyCtorTy =
587 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
588 /*isVarArg*/ false)->getPointerTo();
589 // typedef void (*kmpc_dtor)(void *);
590 auto KmpcDtorTy =
591 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
592 ->getPointerTo();
593 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
594 KmpcCopyCtorTy, KmpcDtorTy};
595 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
596 /*isVarArg*/ false);
597 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
598 break;
599 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000600 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000601 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
602 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000603 llvm::Type *TypeParams[] = {
604 getIdentTyPointerTy(), CGM.Int32Ty,
605 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
606 llvm::FunctionType *FnTy =
607 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
608 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
609 break;
610 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000611 case OMPRTL__kmpc_cancel_barrier: {
612 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
613 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000614 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
615 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000616 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
617 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000618 break;
619 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000620 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000621 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000622 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
623 llvm::FunctionType *FnTy =
624 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
625 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
626 break;
627 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000628 case OMPRTL__kmpc_for_static_fini: {
629 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
630 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
631 llvm::FunctionType *FnTy =
632 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
634 break;
635 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000636 case OMPRTL__kmpc_push_num_threads: {
637 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
638 // kmp_int32 num_threads)
639 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
640 CGM.Int32Ty};
641 llvm::FunctionType *FnTy =
642 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
643 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
644 break;
645 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000646 case OMPRTL__kmpc_serialized_parallel: {
647 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
648 // global_tid);
649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
650 llvm::FunctionType *FnTy =
651 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
652 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
653 break;
654 }
655 case OMPRTL__kmpc_end_serialized_parallel: {
656 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
657 // global_tid);
658 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
659 llvm::FunctionType *FnTy =
660 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
661 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
662 break;
663 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000664 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000665 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000666 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
667 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000668 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000669 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
670 break;
671 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000672 case OMPRTL__kmpc_master: {
673 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
674 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
675 llvm::FunctionType *FnTy =
676 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
677 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
678 break;
679 }
680 case OMPRTL__kmpc_end_master: {
681 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
682 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
683 llvm::FunctionType *FnTy =
684 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
685 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
686 break;
687 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000688 case OMPRTL__kmpc_omp_taskyield: {
689 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
690 // int end_part);
691 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
692 llvm::FunctionType *FnTy =
693 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
694 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
695 break;
696 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000697 case OMPRTL__kmpc_single: {
698 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
699 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
700 llvm::FunctionType *FnTy =
701 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
702 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
703 break;
704 }
705 case OMPRTL__kmpc_end_single: {
706 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
707 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
708 llvm::FunctionType *FnTy =
709 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
710 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
711 break;
712 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000713 case OMPRTL__kmpc_omp_task_alloc: {
714 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
715 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
716 // kmp_routine_entry_t *task_entry);
717 assert(KmpRoutineEntryPtrTy != nullptr &&
718 "Type kmp_routine_entry_t must be created.");
719 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
720 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
721 // Return void * and then cast to particular kmp_task_t type.
722 llvm::FunctionType *FnTy =
723 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
724 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
725 break;
726 }
727 case OMPRTL__kmpc_omp_task: {
728 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
729 // *new_task);
730 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
731 CGM.VoidPtrTy};
732 llvm::FunctionType *FnTy =
733 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
734 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
735 break;
736 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000737 case OMPRTL__kmpc_copyprivate: {
738 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +0000739 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +0000740 // kmp_int32 didit);
741 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
742 auto *CpyFnTy =
743 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +0000744 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +0000745 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
746 CGM.Int32Ty};
747 llvm::FunctionType *FnTy =
748 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
749 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
750 break;
751 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000752 case OMPRTL__kmpc_reduce: {
753 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
754 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
755 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
756 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
757 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
758 /*isVarArg=*/false);
759 llvm::Type *TypeParams[] = {
760 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
761 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
762 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
763 llvm::FunctionType *FnTy =
764 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
765 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
766 break;
767 }
768 case OMPRTL__kmpc_reduce_nowait: {
769 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
770 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
771 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
772 // *lck);
773 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
774 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
775 /*isVarArg=*/false);
776 llvm::Type *TypeParams[] = {
777 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
778 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
779 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
780 llvm::FunctionType *FnTy =
781 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
782 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
783 break;
784 }
785 case OMPRTL__kmpc_end_reduce: {
786 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
787 // kmp_critical_name *lck);
788 llvm::Type *TypeParams[] = {
789 getIdentTyPointerTy(), CGM.Int32Ty,
790 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
791 llvm::FunctionType *FnTy =
792 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
793 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
794 break;
795 }
796 case OMPRTL__kmpc_end_reduce_nowait: {
797 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
798 // kmp_critical_name *lck);
799 llvm::Type *TypeParams[] = {
800 getIdentTyPointerTy(), CGM.Int32Ty,
801 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
802 llvm::FunctionType *FnTy =
803 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
804 RTLFn =
805 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
806 break;
807 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000808 case OMPRTL__kmpc_omp_task_begin_if0: {
809 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
810 // *new_task);
811 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
812 CGM.VoidPtrTy};
813 llvm::FunctionType *FnTy =
814 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
815 RTLFn =
816 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
817 break;
818 }
819 case OMPRTL__kmpc_omp_task_complete_if0: {
820 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
821 // *new_task);
822 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
823 CGM.VoidPtrTy};
824 llvm::FunctionType *FnTy =
825 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
826 RTLFn = CGM.CreateRuntimeFunction(FnTy,
827 /*Name=*/"__kmpc_omp_task_complete_if0");
828 break;
829 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000830 case OMPRTL__kmpc_ordered: {
831 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
832 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
833 llvm::FunctionType *FnTy =
834 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
835 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
836 break;
837 }
838 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000839 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000840 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
841 llvm::FunctionType *FnTy =
842 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
843 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
844 break;
845 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +0000846 case OMPRTL__kmpc_omp_taskwait: {
847 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
848 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
849 llvm::FunctionType *FnTy =
850 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
851 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
852 break;
853 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000854 case OMPRTL__kmpc_taskgroup: {
855 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
856 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
857 llvm::FunctionType *FnTy =
858 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
859 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
860 break;
861 }
862 case OMPRTL__kmpc_end_taskgroup: {
863 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
864 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
865 llvm::FunctionType *FnTy =
866 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
867 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
868 break;
869 }
Alexey Bataev7f210c62015-06-18 13:40:03 +0000870 case OMPRTL__kmpc_push_proc_bind: {
871 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
872 // int proc_bind)
873 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
874 llvm::FunctionType *FnTy =
875 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
876 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
877 break;
878 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +0000879 case OMPRTL__kmpc_omp_task_with_deps: {
880 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
881 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
882 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
883 llvm::Type *TypeParams[] = {
884 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
885 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
886 llvm::FunctionType *FnTy =
887 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
888 RTLFn =
889 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
890 break;
891 }
892 case OMPRTL__kmpc_omp_wait_deps: {
893 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
894 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
895 // kmp_depend_info_t *noalias_dep_list);
896 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
897 CGM.Int32Ty, CGM.VoidPtrTy,
898 CGM.Int32Ty, CGM.VoidPtrTy};
899 llvm::FunctionType *FnTy =
900 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
901 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
902 break;
903 }
Alexey Bataev0f34da12015-07-02 04:17:07 +0000904 case OMPRTL__kmpc_cancellationpoint: {
905 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
906 // global_tid, kmp_int32 cncl_kind)
907 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
908 llvm::FunctionType *FnTy =
909 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
910 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
911 break;
912 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +0000913 case OMPRTL__kmpc_cancel: {
914 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
915 // kmp_int32 cncl_kind)
916 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
917 llvm::FunctionType *FnTy =
918 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
919 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
920 break;
921 }
Samuel Antaobed3c462015-10-02 16:14:20 +0000922 case OMPRTL__tgt_target: {
923 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
924 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
925 // *arg_types);
926 llvm::Type *TypeParams[] = {CGM.Int32Ty,
927 CGM.VoidPtrTy,
928 CGM.Int32Ty,
929 CGM.VoidPtrPtrTy,
930 CGM.VoidPtrPtrTy,
931 CGM.SizeTy->getPointerTo(),
932 CGM.Int32Ty->getPointerTo()};
933 llvm::FunctionType *FnTy =
934 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
935 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
936 break;
937 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000938 case OMPRTL__tgt_register_lib: {
939 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
940 QualType ParamTy =
941 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
942 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
943 llvm::FunctionType *FnTy =
944 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
945 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
946 break;
947 }
948 case OMPRTL__tgt_unregister_lib: {
949 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
950 QualType ParamTy =
951 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
952 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
953 llvm::FunctionType *FnTy =
954 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
955 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
956 break;
957 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000958 }
959 return RTLFn;
960}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000961
Alexander Musman21212e42015-03-13 10:38:23 +0000962llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
963 bool IVSigned) {
964 assert((IVSize == 32 || IVSize == 64) &&
965 "IV size is not compatible with the omp runtime");
966 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
967 : "__kmpc_for_static_init_4u")
968 : (IVSigned ? "__kmpc_for_static_init_8"
969 : "__kmpc_for_static_init_8u");
970 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
971 auto PtrTy = llvm::PointerType::getUnqual(ITy);
972 llvm::Type *TypeParams[] = {
973 getIdentTyPointerTy(), // loc
974 CGM.Int32Ty, // tid
975 CGM.Int32Ty, // schedtype
976 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
977 PtrTy, // p_lower
978 PtrTy, // p_upper
979 PtrTy, // p_stride
980 ITy, // incr
981 ITy // chunk
982 };
983 llvm::FunctionType *FnTy =
984 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
985 return CGM.CreateRuntimeFunction(FnTy, Name);
986}
987
Alexander Musman92bdaab2015-03-12 13:37:50 +0000988llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
989 bool IVSigned) {
990 assert((IVSize == 32 || IVSize == 64) &&
991 "IV size is not compatible with the omp runtime");
992 auto Name =
993 IVSize == 32
994 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
995 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
996 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
997 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
998 CGM.Int32Ty, // tid
999 CGM.Int32Ty, // schedtype
1000 ITy, // lower
1001 ITy, // upper
1002 ITy, // stride
1003 ITy // chunk
1004 };
1005 llvm::FunctionType *FnTy =
1006 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1007 return CGM.CreateRuntimeFunction(FnTy, Name);
1008}
1009
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001010llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1011 bool IVSigned) {
1012 assert((IVSize == 32 || IVSize == 64) &&
1013 "IV size is not compatible with the omp runtime");
1014 auto Name =
1015 IVSize == 32
1016 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1017 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1018 llvm::Type *TypeParams[] = {
1019 getIdentTyPointerTy(), // loc
1020 CGM.Int32Ty, // tid
1021 };
1022 llvm::FunctionType *FnTy =
1023 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1024 return CGM.CreateRuntimeFunction(FnTy, Name);
1025}
1026
Alexander Musman92bdaab2015-03-12 13:37:50 +00001027llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1028 bool IVSigned) {
1029 assert((IVSize == 32 || IVSize == 64) &&
1030 "IV size is not compatible with the omp runtime");
1031 auto Name =
1032 IVSize == 32
1033 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1034 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1035 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1036 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1037 llvm::Type *TypeParams[] = {
1038 getIdentTyPointerTy(), // loc
1039 CGM.Int32Ty, // tid
1040 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1041 PtrTy, // p_lower
1042 PtrTy, // p_upper
1043 PtrTy // p_stride
1044 };
1045 llvm::FunctionType *FnTy =
1046 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1047 return CGM.CreateRuntimeFunction(FnTy, Name);
1048}
1049
Alexey Bataev97720002014-11-11 04:05:39 +00001050llvm::Constant *
1051CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001052 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1053 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001054 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001055 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001056 Twine(CGM.getMangledName(VD)) + ".cache.");
1057}
1058
John McCall7f416cc2015-09-08 08:05:57 +00001059Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1060 const VarDecl *VD,
1061 Address VDAddr,
1062 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001063 if (CGM.getLangOpts().OpenMPUseTLS &&
1064 CGM.getContext().getTargetInfo().isTLSSupported())
1065 return VDAddr;
1066
John McCall7f416cc2015-09-08 08:05:57 +00001067 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001068 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001069 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1070 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001071 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1072 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001073 return Address(CGF.EmitRuntimeCall(
1074 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1075 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001076}
1077
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001078void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001079 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001080 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1081 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1082 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001083 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1084 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001085 OMPLoc);
1086 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1087 // to register constructor/destructor for variable.
1088 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001089 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1090 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001091 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001092 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001093 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001094}
1095
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001096llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001097 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001098 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001099 if (CGM.getLangOpts().OpenMPUseTLS &&
1100 CGM.getContext().getTargetInfo().isTLSSupported())
1101 return nullptr;
1102
Alexey Bataev97720002014-11-11 04:05:39 +00001103 VD = VD->getDefinition(CGM.getContext());
1104 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1105 ThreadPrivateWithDefinition.insert(VD);
1106 QualType ASTTy = VD->getType();
1107
1108 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1109 auto Init = VD->getAnyInitializer();
1110 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1111 // Generate function that re-emits the declaration's initializer into the
1112 // threadprivate copy of the variable VD
1113 CodeGenFunction CtorCGF(CGM);
1114 FunctionArgList Args;
1115 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1116 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1117 Args.push_back(&Dst);
1118
1119 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1120 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
1121 /*isVariadic=*/false);
1122 auto FTy = CGM.getTypes().GetFunctionType(FI);
1123 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001124 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001125 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1126 Args, SourceLocation());
1127 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001128 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001129 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001130 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1131 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1132 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001133 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1134 /*IsInitializer=*/true);
1135 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001136 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001137 CGM.getContext().VoidPtrTy, Dst.getLocation());
1138 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1139 CtorCGF.FinishFunction();
1140 Ctor = Fn;
1141 }
1142 if (VD->getType().isDestructedType() != QualType::DK_none) {
1143 // Generate function that emits destructor call for the threadprivate copy
1144 // of the variable VD
1145 CodeGenFunction DtorCGF(CGM);
1146 FunctionArgList Args;
1147 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1148 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1149 Args.push_back(&Dst);
1150
1151 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1152 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
1153 /*isVariadic=*/false);
1154 auto FTy = CGM.getTypes().GetFunctionType(FI);
1155 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001156 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001157 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1158 SourceLocation());
1159 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1160 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001161 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1162 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001163 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1164 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1165 DtorCGF.FinishFunction();
1166 Dtor = Fn;
1167 }
1168 // Do not emit init function if it is not required.
1169 if (!Ctor && !Dtor)
1170 return nullptr;
1171
1172 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1173 auto CopyCtorTy =
1174 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1175 /*isVarArg=*/false)->getPointerTo();
1176 // Copying constructor for the threadprivate variable.
1177 // Must be NULL - reserved by runtime, but currently it requires that this
1178 // parameter is always NULL. Otherwise it fires assertion.
1179 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1180 if (Ctor == nullptr) {
1181 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1182 /*isVarArg=*/false)->getPointerTo();
1183 Ctor = llvm::Constant::getNullValue(CtorTy);
1184 }
1185 if (Dtor == nullptr) {
1186 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1187 /*isVarArg=*/false)->getPointerTo();
1188 Dtor = llvm::Constant::getNullValue(DtorTy);
1189 }
1190 if (!CGF) {
1191 auto InitFunctionTy =
1192 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1193 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001194 InitFunctionTy, ".__omp_threadprivate_init_.",
1195 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001196 CodeGenFunction InitCGF(CGM);
1197 FunctionArgList ArgList;
1198 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1199 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1200 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001201 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001202 InitCGF.FinishFunction();
1203 return InitFunction;
1204 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001205 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001206 }
1207 return nullptr;
1208}
1209
Alexey Bataev1d677132015-04-22 13:57:31 +00001210/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1211/// function. Here is the logic:
1212/// if (Cond) {
1213/// ThenGen();
1214/// } else {
1215/// ElseGen();
1216/// }
1217static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1218 const RegionCodeGenTy &ThenGen,
1219 const RegionCodeGenTy &ElseGen) {
1220 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1221
1222 // If the condition constant folds and can be elided, try to avoid emitting
1223 // the condition and the dead arm of the if/else.
1224 bool CondConstant;
1225 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1226 CodeGenFunction::RunCleanupsScope Scope(CGF);
1227 if (CondConstant) {
1228 ThenGen(CGF);
1229 } else {
1230 ElseGen(CGF);
1231 }
1232 return;
1233 }
1234
1235 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1236 // emit the conditional branch.
1237 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1238 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1239 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1240 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1241
1242 // Emit the 'then' code.
1243 CGF.EmitBlock(ThenBlock);
1244 {
1245 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1246 ThenGen(CGF);
1247 }
1248 CGF.EmitBranch(ContBlock);
1249 // Emit the 'else' code if present.
1250 {
1251 // There is no need to emit line number for unconditional branch.
1252 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1253 CGF.EmitBlock(ElseBlock);
1254 }
1255 {
1256 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1257 ElseGen(CGF);
1258 }
1259 {
1260 // There is no need to emit line number for unconditional branch.
1261 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1262 CGF.EmitBranch(ContBlock);
1263 }
1264 // Emit the continuation block for code after the if.
1265 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001266}
1267
Alexey Bataev1d677132015-04-22 13:57:31 +00001268void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1269 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001270 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001271 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001272 if (!CGF.HaveInsertPoint())
1273 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001274 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001275 auto &&ThenGen = [this, OutlinedFn, CapturedVars,
1276 RTLoc](CodeGenFunction &CGF) {
1277 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1278 llvm::Value *Args[] = {
1279 RTLoc,
1280 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1281 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
1282 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1283 RealArgs.append(std::begin(Args), std::end(Args));
1284 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1285
1286 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1287 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1288 };
1289 auto &&ElseGen = [this, OutlinedFn, CapturedVars, RTLoc,
1290 Loc](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001291 auto ThreadID = getThreadID(CGF, Loc);
1292 // Build calls:
1293 // __kmpc_serialized_parallel(&Loc, GTid);
1294 llvm::Value *Args[] = {RTLoc, ThreadID};
1295 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1296 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001297
Alexey Bataev1d677132015-04-22 13:57:31 +00001298 // OutlinedFn(&GTid, &zero, CapturedStruct);
1299 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001300 Address ZeroAddr =
1301 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1302 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001303 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001304 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1305 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1306 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1307 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001308 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001309
Alexey Bataev1d677132015-04-22 13:57:31 +00001310 // __kmpc_end_serialized_parallel(&Loc, GTid);
1311 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1312 CGF.EmitRuntimeCall(
1313 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1314 };
1315 if (IfCond) {
1316 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1317 } else {
1318 CodeGenFunction::RunCleanupsScope Scope(CGF);
1319 ThenGen(CGF);
1320 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001321}
1322
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001323// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001324// thread-ID variable (it is passed in a first argument of the outlined function
1325// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1326// regular serial code region, get thread ID by calling kmp_int32
1327// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1328// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001329Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1330 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001331 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001332 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001333 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001334 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001335
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001336 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001337 auto Int32Ty =
1338 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1339 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1340 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001341 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001342
1343 return ThreadIDTemp;
1344}
1345
Alexey Bataev97720002014-11-11 04:05:39 +00001346llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001347CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001348 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001349 SmallString<256> Buffer;
1350 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001351 Out << Name;
1352 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001353 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1354 if (Elem.second) {
1355 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001356 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001357 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001358 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001359
David Blaikie13156b62014-11-19 03:06:06 +00001360 return Elem.second = new llvm::GlobalVariable(
1361 CGM.getModule(), Ty, /*IsConstant*/ false,
1362 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1363 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001364}
1365
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001366llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001367 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001368 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001369}
1370
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001371namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001372template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001373 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001374 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001375
1376public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001377 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1378 : Callee(Callee) {
1379 assert(CleanupArgs.size() == N);
1380 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1381 }
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001382 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001383 if (!CGF.HaveInsertPoint())
1384 return;
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001385 CGF.EmitRuntimeCall(Callee, Args);
1386 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001387};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001388} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001389
1390void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1391 StringRef CriticalName,
1392 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00001393 SourceLocation Loc, const Expr *Hint) {
1394 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001395 // CriticalOpGen();
1396 // __kmpc_end_critical(ident_t *, gtid, Lock);
1397 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00001398 if (!CGF.HaveInsertPoint())
1399 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00001400 CodeGenFunction::RunCleanupsScope Scope(CGF);
1401 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1402 getCriticalRegionLock(CriticalName)};
1403 if (Hint) {
1404 llvm::SmallVector<llvm::Value *, 8> ArgsWithHint(std::begin(Args),
1405 std::end(Args));
1406 auto *HintVal = CGF.EmitScalarExpr(Hint);
1407 ArgsWithHint.push_back(
1408 CGF.Builder.CreateIntCast(HintVal, CGM.IntPtrTy, /*isSigned=*/false));
1409 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical_with_hint),
1410 ArgsWithHint);
1411 } else
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001412 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataevfc57d162015-12-15 10:55:09 +00001413 // Build a call to __kmpc_end_critical
1414 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1415 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1416 llvm::makeArrayRef(Args));
1417 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001418}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001419
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001420static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001421 OpenMPDirectiveKind Kind, SourceLocation Loc,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001422 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001423 llvm::Value *CallBool = CGF.EmitScalarConversion(
1424 IfCond,
1425 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001426 CGF.getContext().BoolTy, Loc);
Alexey Bataev8d690652014-12-04 07:23:53 +00001427
1428 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1429 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1430 // Generate the branch (If-stmt)
1431 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1432 CGF.EmitBlock(ThenBlock);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001433 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001434 // Emit the rest of bblocks/branches
1435 CGF.EmitBranch(ContBlock);
1436 CGF.EmitBlock(ContBlock, true);
1437}
1438
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001439void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001440 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001441 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001442 if (!CGF.HaveInsertPoint())
1443 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00001444 // if(__kmpc_master(ident_t *, gtid)) {
1445 // MasterOpGen();
1446 // __kmpc_end_master(ident_t *, gtid);
1447 // }
1448 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001449 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001450 auto *IsMaster =
1451 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001452 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1453 MasterCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001454 emitIfStmt(
1455 CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1456 CodeGenFunction::RunCleanupsScope Scope(CGF);
1457 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1458 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1459 llvm::makeArrayRef(Args));
1460 MasterOpGen(CGF);
1461 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001462}
1463
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001464void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1465 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001466 if (!CGF.HaveInsertPoint())
1467 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00001468 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1469 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001470 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001471 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001472 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001473}
1474
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001475void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1476 const RegionCodeGenTy &TaskgroupOpGen,
1477 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001478 if (!CGF.HaveInsertPoint())
1479 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001480 // __kmpc_taskgroup(ident_t *, gtid);
1481 // TaskgroupOpGen();
1482 // __kmpc_end_taskgroup(ident_t *, gtid);
1483 // Prepare arguments and build a call to __kmpc_taskgroup
1484 {
1485 CodeGenFunction::RunCleanupsScope Scope(CGF);
1486 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1487 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1488 // Build a call to __kmpc_end_taskgroup
1489 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1490 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1491 llvm::makeArrayRef(Args));
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001492 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001493 }
1494}
1495
John McCall7f416cc2015-09-08 08:05:57 +00001496/// Given an array of pointers to variables, project the address of a
1497/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001498static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
1499 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00001500 // Pull out the pointer to the variable.
1501 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001502 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00001503 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1504
1505 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00001506 Addr = CGF.Builder.CreateElementBitCast(
1507 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001508 return Addr;
1509}
1510
Alexey Bataeva63048e2015-03-23 06:18:07 +00001511static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001512 CodeGenModule &CGM, llvm::Type *ArgsType,
1513 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1514 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001515 auto &C = CGM.getContext();
1516 // void copy_func(void *LHSArg, void *RHSArg);
1517 FunctionArgList Args;
1518 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1519 C.VoidPtrTy);
1520 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1521 C.VoidPtrTy);
1522 Args.push_back(&LHSArg);
1523 Args.push_back(&RHSArg);
1524 FunctionType::ExtInfo EI;
1525 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1526 C.VoidTy, Args, EI, /*isVariadic=*/false);
1527 auto *Fn = llvm::Function::Create(
1528 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1529 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00001530 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001531 CodeGenFunction CGF(CGM);
1532 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001533 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001534 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00001535 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1536 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1537 ArgsType), CGF.getPointerAlign());
1538 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1539 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1540 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001541 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1542 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1543 // ...
1544 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001545 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001546 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1547 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1548
1549 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1550 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1551
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001552 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1553 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001554 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001555 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001556 CGF.FinishFunction();
1557 return Fn;
1558}
1559
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001560void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001561 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001562 SourceLocation Loc,
1563 ArrayRef<const Expr *> CopyprivateVars,
1564 ArrayRef<const Expr *> SrcExprs,
1565 ArrayRef<const Expr *> DstExprs,
1566 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001567 if (!CGF.HaveInsertPoint())
1568 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001569 assert(CopyprivateVars.size() == SrcExprs.size() &&
1570 CopyprivateVars.size() == DstExprs.size() &&
1571 CopyprivateVars.size() == AssignmentOps.size());
1572 auto &C = CGM.getContext();
1573 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001574 // if(__kmpc_single(ident_t *, gtid)) {
1575 // SingleOpGen();
1576 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001577 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001578 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001579 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1580 // <copy_func>, did_it);
1581
John McCall7f416cc2015-09-08 08:05:57 +00001582 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001583 if (!CopyprivateVars.empty()) {
1584 // int32 did_it = 0;
1585 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1586 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00001587 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001588 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001589 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001590 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001591 auto *IsSingle =
1592 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001593 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1594 SingleCallEndCleanup;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001595 emitIfStmt(
1596 CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
1597 CodeGenFunction::RunCleanupsScope Scope(CGF);
1598 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
1599 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1600 llvm::makeArrayRef(Args));
1601 SingleOpGen(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001602 if (DidIt.isValid()) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001603 // did_it = 1;
John McCall7f416cc2015-09-08 08:05:57 +00001604 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001605 }
1606 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001607 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1608 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00001609 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001610 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1611 auto CopyprivateArrayTy =
1612 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1613 /*IndexTypeQuals=*/0);
1614 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00001615 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001616 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1617 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00001618 Address Elem = CGF.Builder.CreateConstArrayGEP(
1619 CopyprivateList, I, CGF.getPointerSize());
1620 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00001621 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00001622 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
1623 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001624 }
1625 // Build function that copies private values from single region to all other
1626 // threads in the corresponding parallel region.
1627 auto *CpyFn = emitCopyprivateCopyFunction(
1628 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001629 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00001630 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00001631 Address CL =
1632 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1633 CGF.VoidPtrTy);
1634 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001635 llvm::Value *Args[] = {
1636 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1637 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001638 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00001639 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001640 CpyFn, // void (*) (void *, void *) <copy_func>
1641 DidItVal // i32 did_it
1642 };
1643 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1644 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001645}
1646
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001647void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1648 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00001649 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001650 if (!CGF.HaveInsertPoint())
1651 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001652 // __kmpc_ordered(ident_t *, gtid);
1653 // OrderedOpGen();
1654 // __kmpc_end_ordered(ident_t *, gtid);
1655 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00001656 CodeGenFunction::RunCleanupsScope Scope(CGF);
1657 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001658 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1659 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1660 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001661 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001662 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1663 llvm::makeArrayRef(Args));
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001664 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00001665 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001666}
1667
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001668void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00001669 OpenMPDirectiveKind Kind, bool EmitChecks,
1670 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001671 if (!CGF.HaveInsertPoint())
1672 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001673 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001674 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001675 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1676 if (Kind == OMPD_for) {
1677 Flags =
1678 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1679 } else if (Kind == OMPD_sections) {
1680 Flags = static_cast<OpenMPLocationFlags>(Flags |
1681 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1682 } else if (Kind == OMPD_single) {
1683 Flags =
1684 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1685 } else if (Kind == OMPD_barrier) {
1686 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1687 } else {
1688 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1689 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001690 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
1691 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001692 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1693 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001694 if (auto *OMPRegionInfo =
1695 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00001696 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001697 auto *Result = CGF.EmitRuntimeCall(
1698 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001699 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001700 // if (__kmpc_cancel_barrier()) {
1701 // exit from construct;
1702 // }
1703 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
1704 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
1705 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
1706 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
1707 CGF.EmitBlock(ExitBB);
1708 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00001709 auto CancelDestination =
1710 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001711 CGF.EmitBranchThroughCleanup(CancelDestination);
1712 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
1713 }
1714 return;
1715 }
1716 }
1717 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001718}
1719
Alexander Musmanc6388682014-12-15 07:07:06 +00001720/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1721/// the enum sched_type in kmp.h).
1722enum OpenMPSchedType {
1723 /// \brief Lower bound for default (unordered) versions.
1724 OMP_sch_lower = 32,
1725 OMP_sch_static_chunked = 33,
1726 OMP_sch_static = 34,
1727 OMP_sch_dynamic_chunked = 35,
1728 OMP_sch_guided_chunked = 36,
1729 OMP_sch_runtime = 37,
1730 OMP_sch_auto = 38,
1731 /// \brief Lower bound for 'ordered' versions.
1732 OMP_ord_lower = 64,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001733 OMP_ord_static_chunked = 65,
1734 OMP_ord_static = 66,
1735 OMP_ord_dynamic_chunked = 67,
1736 OMP_ord_guided_chunked = 68,
1737 OMP_ord_runtime = 69,
1738 OMP_ord_auto = 70,
1739 OMP_sch_default = OMP_sch_static,
Alexander Musmanc6388682014-12-15 07:07:06 +00001740};
1741
1742/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1743static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001744 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001745 switch (ScheduleKind) {
1746 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001747 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
1748 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00001749 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001750 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001751 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001752 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001753 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001754 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
1755 case OMPC_SCHEDULE_auto:
1756 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00001757 case OMPC_SCHEDULE_unknown:
1758 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001759 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00001760 }
1761 llvm_unreachable("Unexpected runtime schedule");
1762}
1763
1764bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1765 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001766 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00001767 return Schedule == OMP_sch_static;
1768}
1769
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001770bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001771 auto Schedule =
1772 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001773 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1774 return Schedule != OMP_sch_static;
1775}
1776
John McCall7f416cc2015-09-08 08:05:57 +00001777void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
1778 SourceLocation Loc,
1779 OpenMPScheduleClauseKind ScheduleKind,
1780 unsigned IVSize, bool IVSigned,
1781 bool Ordered, llvm::Value *UB,
1782 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001783 if (!CGF.HaveInsertPoint())
1784 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001785 OpenMPSchedType Schedule =
1786 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00001787 assert(Ordered ||
1788 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
1789 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
1790 // Call __kmpc_dispatch_init(
1791 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1792 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1793 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001794
John McCall7f416cc2015-09-08 08:05:57 +00001795 // If the Chunk was not specified in the clause - use default value 1.
1796 if (Chunk == nullptr)
1797 Chunk = CGF.Builder.getIntN(IVSize, 1);
1798 llvm::Value *Args[] = {
1799 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1800 getThreadID(CGF, Loc),
1801 CGF.Builder.getInt32(Schedule), // Schedule type
1802 CGF.Builder.getIntN(IVSize, 0), // Lower
1803 UB, // Upper
1804 CGF.Builder.getIntN(IVSize, 1), // Stride
1805 Chunk // Chunk
1806 };
1807 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1808}
1809
1810void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
1811 SourceLocation Loc,
1812 OpenMPScheduleClauseKind ScheduleKind,
1813 unsigned IVSize, bool IVSigned,
1814 bool Ordered, Address IL, Address LB,
1815 Address UB, Address ST,
1816 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001817 if (!CGF.HaveInsertPoint())
1818 return;
John McCall7f416cc2015-09-08 08:05:57 +00001819 OpenMPSchedType Schedule =
1820 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
1821 assert(!Ordered);
1822 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
1823 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked);
1824
1825 // Call __kmpc_for_static_init(
1826 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1827 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1828 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1829 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1830 if (Chunk == nullptr) {
1831 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
1832 "expected static non-chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00001833 // If the Chunk was not specified in the clause - use default value 1.
Alexander Musman92bdaab2015-03-12 13:37:50 +00001834 Chunk = CGF.Builder.getIntN(IVSize, 1);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001835 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001836 assert((Schedule == OMP_sch_static_chunked ||
1837 Schedule == OMP_ord_static_chunked) &&
1838 "expected static chunked schedule");
Alexander Musman92bdaab2015-03-12 13:37:50 +00001839 }
John McCall7f416cc2015-09-08 08:05:57 +00001840 llvm::Value *Args[] = {
1841 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1842 getThreadID(CGF, Loc),
1843 CGF.Builder.getInt32(Schedule), // Schedule type
1844 IL.getPointer(), // &isLastIter
1845 LB.getPointer(), // &LB
1846 UB.getPointer(), // &UB
1847 ST.getPointer(), // &Stride
1848 CGF.Builder.getIntN(IVSize, 1), // Incr
1849 Chunk // Chunk
1850 };
1851 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001852}
1853
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001854void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
1855 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001856 if (!CGF.HaveInsertPoint())
1857 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00001858 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001859 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1860 getThreadID(CGF, Loc)};
1861 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1862 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001863}
1864
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001865void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
1866 SourceLocation Loc,
1867 unsigned IVSize,
1868 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001869 if (!CGF.HaveInsertPoint())
1870 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001871 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
1872 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1873 getThreadID(CGF, Loc)};
1874 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
1875}
1876
Alexander Musman92bdaab2015-03-12 13:37:50 +00001877llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1878 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00001879 bool IVSigned, Address IL,
1880 Address LB, Address UB,
1881 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001882 // Call __kmpc_dispatch_next(
1883 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1884 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1885 // kmp_int[32|64] *p_stride);
1886 llvm::Value *Args[] = {
1887 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001888 IL.getPointer(), // &isLastIter
1889 LB.getPointer(), // &Lower
1890 UB.getPointer(), // &Upper
1891 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00001892 };
1893 llvm::Value *Call =
1894 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1895 return CGF.EmitScalarConversion(
1896 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001897 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001898}
1899
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001900void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1901 llvm::Value *NumThreads,
1902 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001903 if (!CGF.HaveInsertPoint())
1904 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00001905 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1906 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001907 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001908 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001909 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1910 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001911}
1912
Alexey Bataev7f210c62015-06-18 13:40:03 +00001913void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
1914 OpenMPProcBindClauseKind ProcBind,
1915 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001916 if (!CGF.HaveInsertPoint())
1917 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00001918 // Constants for proc bind value accepted by the runtime.
1919 enum ProcBindTy {
1920 ProcBindFalse = 0,
1921 ProcBindTrue,
1922 ProcBindMaster,
1923 ProcBindClose,
1924 ProcBindSpread,
1925 ProcBindIntel,
1926 ProcBindDefault
1927 } RuntimeProcBind;
1928 switch (ProcBind) {
1929 case OMPC_PROC_BIND_master:
1930 RuntimeProcBind = ProcBindMaster;
1931 break;
1932 case OMPC_PROC_BIND_close:
1933 RuntimeProcBind = ProcBindClose;
1934 break;
1935 case OMPC_PROC_BIND_spread:
1936 RuntimeProcBind = ProcBindSpread;
1937 break;
1938 case OMPC_PROC_BIND_unknown:
1939 llvm_unreachable("Unsupported proc_bind value.");
1940 }
1941 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
1942 llvm::Value *Args[] = {
1943 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1944 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
1945 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
1946}
1947
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001948void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1949 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001950 if (!CGF.HaveInsertPoint())
1951 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001952 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001953 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1954 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001955}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001956
Alexey Bataev62b63b12015-03-10 07:28:44 +00001957namespace {
1958/// \brief Indexes of fields for type kmp_task_t.
1959enum KmpTaskTFields {
1960 /// \brief List of shared variables.
1961 KmpTaskTShareds,
1962 /// \brief Task routine.
1963 KmpTaskTRoutine,
1964 /// \brief Partition id for the untied tasks.
1965 KmpTaskTPartId,
1966 /// \brief Function with call of destructors for private variables.
1967 KmpTaskTDestructors,
1968};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001969} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00001970
Samuel Antaoee8fb302016-01-06 13:42:12 +00001971bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
1972 // FIXME: Add other entries type when they become supported.
1973 return OffloadEntriesTargetRegion.empty();
1974}
1975
1976/// \brief Initialize target region entry.
1977void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
1978 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
1979 StringRef ParentName, unsigned LineNum,
1980 unsigned ColNum, unsigned Order) {
1981 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
1982 "only required for the device "
1983 "code generation.");
1984 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum][ColNum] =
1985 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
1986 ++OffloadingEntriesNum;
1987}
1988
1989void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
1990 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
1991 StringRef ParentName, unsigned LineNum,
1992 unsigned ColNum, llvm::Constant *Addr,
1993 llvm::Constant *ID) {
1994 // If we are emitting code for a target, the entry is already initialized,
1995 // only has to be registered.
1996 if (CGM.getLangOpts().OpenMPIsDevice) {
1997 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum,
1998 ColNum) &&
1999 "Entry must exist.");
2000 auto &Entry = OffloadEntriesTargetRegion[DeviceID][FileID][ParentName]
2001 [LineNum][ColNum];
2002 assert(Entry.isValid() && "Entry not initialized!");
2003 Entry.setAddress(Addr);
2004 Entry.setID(ID);
2005 return;
2006 } else {
2007 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
2008 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum][ColNum] =
2009 Entry;
2010 }
2011}
2012
2013bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
2014 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum,
2015 unsigned ColNum) const {
2016 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2017 if (PerDevice == OffloadEntriesTargetRegion.end())
2018 return false;
2019 auto PerFile = PerDevice->second.find(FileID);
2020 if (PerFile == PerDevice->second.end())
2021 return false;
2022 auto PerParentName = PerFile->second.find(ParentName);
2023 if (PerParentName == PerFile->second.end())
2024 return false;
2025 auto PerLine = PerParentName->second.find(LineNum);
2026 if (PerLine == PerParentName->second.end())
2027 return false;
2028 auto PerColumn = PerLine->second.find(ColNum);
2029 if (PerColumn == PerLine->second.end())
2030 return false;
2031 // Fail if this entry is already registered.
2032 if (PerColumn->second.getAddress() || PerColumn->second.getID())
2033 return false;
2034 return true;
2035}
2036
2037void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2038 const OffloadTargetRegionEntryInfoActTy &Action) {
2039 // Scan all target region entries and perform the provided action.
2040 for (auto &D : OffloadEntriesTargetRegion)
2041 for (auto &F : D.second)
2042 for (auto &P : F.second)
2043 for (auto &L : P.second)
2044 for (auto &C : L.second)
2045 Action(D.first, F.first, P.first(), L.first, C.first, C.second);
2046}
2047
2048/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2049/// \a Codegen. This is used to emit the two functions that register and
2050/// unregister the descriptor of the current compilation unit.
2051static llvm::Function *
2052createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2053 const RegionCodeGenTy &Codegen) {
2054 auto &C = CGM.getContext();
2055 FunctionArgList Args;
2056 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2057 /*Id=*/nullptr, C.VoidPtrTy);
2058 Args.push_back(&DummyPtr);
2059
2060 CodeGenFunction CGF(CGM);
2061 GlobalDecl();
2062 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2063 C.VoidTy, Args, FunctionType::ExtInfo(),
2064 /*isVariadic=*/false);
2065 auto FTy = CGM.getTypes().GetFunctionType(FI);
2066 auto *Fn =
2067 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2068 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2069 Codegen(CGF);
2070 CGF.FinishFunction();
2071 return Fn;
2072}
2073
2074llvm::Function *
2075CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2076
2077 // If we don't have entries or if we are emitting code for the device, we
2078 // don't need to do anything.
2079 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2080 return nullptr;
2081
2082 auto &M = CGM.getModule();
2083 auto &C = CGM.getContext();
2084
2085 // Get list of devices we care about
2086 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2087
2088 // We should be creating an offloading descriptor only if there are devices
2089 // specified.
2090 assert(!Devices.empty() && "No OpenMP offloading devices??");
2091
2092 // Create the external variables that will point to the begin and end of the
2093 // host entries section. These will be defined by the linker.
2094 auto *OffloadEntryTy =
2095 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2096 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2097 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002098 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002099 ".omp_offloading.entries_begin");
2100 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2101 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002102 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002103 ".omp_offloading.entries_end");
2104
2105 // Create all device images
2106 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2107 auto *DeviceImageTy = cast<llvm::StructType>(
2108 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2109
2110 for (unsigned i = 0; i < Devices.size(); ++i) {
2111 StringRef T = Devices[i].getTriple();
2112 auto *ImgBegin = new llvm::GlobalVariable(
2113 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002114 /*Initializer=*/nullptr,
2115 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002116 auto *ImgEnd = new llvm::GlobalVariable(
2117 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002118 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002119
2120 llvm::Constant *Dev =
2121 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2122 HostEntriesBegin, HostEntriesEnd, nullptr);
2123 DeviceImagesEntires.push_back(Dev);
2124 }
2125
2126 // Create device images global array.
2127 llvm::ArrayType *DeviceImagesInitTy =
2128 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2129 llvm::Constant *DeviceImagesInit =
2130 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2131
2132 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2133 M, DeviceImagesInitTy, /*isConstant=*/true,
2134 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2135 ".omp_offloading.device_images");
2136 DeviceImages->setUnnamedAddr(true);
2137
2138 // This is a Zero array to be used in the creation of the constant expressions
2139 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2140 llvm::Constant::getNullValue(CGM.Int32Ty)};
2141
2142 // Create the target region descriptor.
2143 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2144 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2145 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2146 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2147 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2148 Index),
2149 HostEntriesBegin, HostEntriesEnd, nullptr);
2150
2151 auto *Desc = new llvm::GlobalVariable(
2152 M, BinaryDescriptorTy, /*isConstant=*/true,
2153 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2154 ".omp_offloading.descriptor");
2155
2156 // Emit code to register or unregister the descriptor at execution
2157 // startup or closing, respectively.
2158
2159 // Create a variable to drive the registration and unregistration of the
2160 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2161 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2162 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2163 IdentInfo, C.CharTy);
2164
2165 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2166 CGM, ".omp_offloading.descriptor_unreg", [&](CodeGenFunction &CGF) {
2167 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2168 Desc);
2169 });
2170 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2171 CGM, ".omp_offloading.descriptor_reg", [&](CodeGenFunction &CGF) {
2172 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2173 Desc);
2174 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2175 });
2176 return RegFn;
2177}
2178
2179void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *Addr, StringRef Name,
2180 uint64_t Size) {
2181 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2182 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2183 llvm::LLVMContext &C = CGM.getModule().getContext();
2184 llvm::Module &M = CGM.getModule();
2185
2186 // Make sure the address has the right type.
2187 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(Addr, CGM.VoidPtrTy);
2188
2189 // Create constant string with the name.
2190 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2191
2192 llvm::GlobalVariable *Str =
2193 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2194 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2195 ".omp_offloading.entry_name");
2196 Str->setUnnamedAddr(true);
2197 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2198
2199 // Create the entry struct.
2200 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2201 TgtOffloadEntryType, AddrPtr, StrPtr,
2202 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2203 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2204 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2205 EntryInit, ".omp_offloading.entry");
2206
2207 // The entry has to be created in the section the linker expects it to be.
2208 Entry->setSection(".omp_offloading.entries");
2209 // We can't have any padding between symbols, so we need to have 1-byte
2210 // alignment.
2211 Entry->setAlignment(1);
2212 return;
2213}
2214
2215void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2216 // Emit the offloading entries and metadata so that the device codegen side
2217 // can
2218 // easily figure out what to emit. The produced metadata looks like this:
2219 //
2220 // !omp_offload.info = !{!1, ...}
2221 //
2222 // Right now we only generate metadata for function that contain target
2223 // regions.
2224
2225 // If we do not have entries, we dont need to do anything.
2226 if (OffloadEntriesInfoManager.empty())
2227 return;
2228
2229 llvm::Module &M = CGM.getModule();
2230 llvm::LLVMContext &C = M.getContext();
2231 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2232 OrderedEntries(OffloadEntriesInfoManager.size());
2233
2234 // Create the offloading info metadata node.
2235 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2236
2237 // Auxiliar methods to create metadata values and strings.
2238 auto getMDInt = [&](unsigned v) {
2239 return llvm::ConstantAsMetadata::get(
2240 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2241 };
2242
2243 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2244
2245 // Create function that emits metadata for each target region entry;
2246 auto &&TargetRegionMetadataEmitter = [&](
2247 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
2248 unsigned Column,
2249 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2250 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2251 // Generate metadata for target regions. Each entry of this metadata
2252 // contains:
2253 // - Entry 0 -> Kind of this type of metadata (0).
2254 // - Entry 1 -> Device ID of the file where the entry was identified.
2255 // - Entry 2 -> File ID of the file where the entry was identified.
2256 // - Entry 3 -> Mangled name of the function where the entry was identified.
2257 // - Entry 4 -> Line in the file where the entry was identified.
2258 // - Entry 5 -> Column in the file where the entry was identified.
2259 // - Entry 6 -> Order the entry was created.
2260 // The first element of the metadata node is the kind.
2261 Ops.push_back(getMDInt(E.getKind()));
2262 Ops.push_back(getMDInt(DeviceID));
2263 Ops.push_back(getMDInt(FileID));
2264 Ops.push_back(getMDString(ParentName));
2265 Ops.push_back(getMDInt(Line));
2266 Ops.push_back(getMDInt(Column));
2267 Ops.push_back(getMDInt(E.getOrder()));
2268
2269 // Save this entry in the right position of the ordered entries array.
2270 OrderedEntries[E.getOrder()] = &E;
2271
2272 // Add metadata to the named metadata node.
2273 MD->addOperand(llvm::MDNode::get(C, Ops));
2274 };
2275
2276 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2277 TargetRegionMetadataEmitter);
2278
2279 for (auto *E : OrderedEntries) {
2280 assert(E && "All ordered entries must exist!");
2281 if (auto *CE =
2282 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2283 E)) {
2284 assert(CE->getID() && CE->getAddress() &&
2285 "Entry ID and Addr are invalid!");
2286 createOffloadEntry(CE->getID(), CE->getAddress()->getName(), /*Size=*/0);
2287 } else
2288 llvm_unreachable("Unsupported entry kind.");
2289 }
2290}
2291
2292/// \brief Loads all the offload entries information from the host IR
2293/// metadata.
2294void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2295 // If we are in target mode, load the metadata from the host IR. This code has
2296 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2297
2298 if (!CGM.getLangOpts().OpenMPIsDevice)
2299 return;
2300
2301 if (CGM.getLangOpts().OMPHostIRFile.empty())
2302 return;
2303
2304 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2305 if (Buf.getError())
2306 return;
2307
2308 llvm::LLVMContext C;
2309 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2310
2311 if (ME.getError())
2312 return;
2313
2314 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2315 if (!MD)
2316 return;
2317
2318 for (auto I : MD->operands()) {
2319 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2320
2321 auto getMDInt = [&](unsigned Idx) {
2322 llvm::ConstantAsMetadata *V =
2323 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2324 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2325 };
2326
2327 auto getMDString = [&](unsigned Idx) {
2328 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2329 return V->getString();
2330 };
2331
2332 switch (getMDInt(0)) {
2333 default:
2334 llvm_unreachable("Unexpected metadata!");
2335 break;
2336 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2337 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2338 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2339 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2340 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
2341 /*Column=*/getMDInt(5), /*Order=*/getMDInt(6));
2342 break;
2343 }
2344 }
2345}
2346
Alexey Bataev62b63b12015-03-10 07:28:44 +00002347void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2348 if (!KmpRoutineEntryPtrTy) {
2349 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2350 auto &C = CGM.getContext();
2351 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2352 FunctionProtoType::ExtProtoInfo EPI;
2353 KmpRoutineEntryPtrQTy = C.getPointerType(
2354 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2355 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2356 }
2357}
2358
Alexey Bataevc71a4092015-09-11 10:29:41 +00002359static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2360 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002361 auto *Field = FieldDecl::Create(
2362 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2363 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2364 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2365 Field->setAccess(AS_public);
2366 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002367 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002368}
2369
Samuel Antaoee8fb302016-01-06 13:42:12 +00002370QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2371
2372 // Make sure the type of the entry is already created. This is the type we
2373 // have to create:
2374 // struct __tgt_offload_entry{
2375 // void *addr; // Pointer to the offload entry info.
2376 // // (function or global)
2377 // char *name; // Name of the function or global.
2378 // size_t size; // Size of the entry info (0 if it a function).
2379 // };
2380 if (TgtOffloadEntryQTy.isNull()) {
2381 ASTContext &C = CGM.getContext();
2382 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2383 RD->startDefinition();
2384 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2385 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2386 addFieldToRecordDecl(C, RD, C.getSizeType());
2387 RD->completeDefinition();
2388 TgtOffloadEntryQTy = C.getRecordType(RD);
2389 }
2390 return TgtOffloadEntryQTy;
2391}
2392
2393QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2394 // These are the types we need to build:
2395 // struct __tgt_device_image{
2396 // void *ImageStart; // Pointer to the target code start.
2397 // void *ImageEnd; // Pointer to the target code end.
2398 // // We also add the host entries to the device image, as it may be useful
2399 // // for the target runtime to have access to that information.
2400 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2401 // // the entries.
2402 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2403 // // entries (non inclusive).
2404 // };
2405 if (TgtDeviceImageQTy.isNull()) {
2406 ASTContext &C = CGM.getContext();
2407 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2408 RD->startDefinition();
2409 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2410 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2411 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2412 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2413 RD->completeDefinition();
2414 TgtDeviceImageQTy = C.getRecordType(RD);
2415 }
2416 return TgtDeviceImageQTy;
2417}
2418
2419QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2420 // struct __tgt_bin_desc{
2421 // int32_t NumDevices; // Number of devices supported.
2422 // __tgt_device_image *DeviceImages; // Arrays of device images
2423 // // (one per device).
2424 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
2425 // // entries.
2426 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2427 // // entries (non inclusive).
2428 // };
2429 if (TgtBinaryDescriptorQTy.isNull()) {
2430 ASTContext &C = CGM.getContext();
2431 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2432 RD->startDefinition();
2433 addFieldToRecordDecl(
2434 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2435 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2436 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2437 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2438 RD->completeDefinition();
2439 TgtBinaryDescriptorQTy = C.getRecordType(RD);
2440 }
2441 return TgtBinaryDescriptorQTy;
2442}
2443
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002444namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00002445struct PrivateHelpersTy {
2446 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
2447 const VarDecl *PrivateElemInit)
2448 : Original(Original), PrivateCopy(PrivateCopy),
2449 PrivateElemInit(PrivateElemInit) {}
2450 const VarDecl *Original;
2451 const VarDecl *PrivateCopy;
2452 const VarDecl *PrivateElemInit;
2453};
2454typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00002455} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002456
Alexey Bataev9e034042015-05-05 04:05:12 +00002457static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00002458createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002459 if (!Privates.empty()) {
2460 auto &C = CGM.getContext();
2461 // Build struct .kmp_privates_t. {
2462 // /* private vars */
2463 // };
2464 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
2465 RD->startDefinition();
2466 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00002467 auto *VD = Pair.second.Original;
2468 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002469 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002470 auto *FD = addFieldToRecordDecl(C, RD, Type);
2471 if (VD->hasAttrs()) {
2472 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
2473 E(VD->getAttrs().end());
2474 I != E; ++I)
2475 FD->addAttr(*I);
2476 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002477 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002478 RD->completeDefinition();
2479 return RD;
2480 }
2481 return nullptr;
2482}
2483
Alexey Bataev9e034042015-05-05 04:05:12 +00002484static RecordDecl *
2485createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002486 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002487 auto &C = CGM.getContext();
2488 // Build struct kmp_task_t {
2489 // void * shareds;
2490 // kmp_routine_entry_t routine;
2491 // kmp_int32 part_id;
2492 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002493 // };
2494 auto *RD = C.buildImplicitRecord("kmp_task_t");
2495 RD->startDefinition();
2496 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2497 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2498 addFieldToRecordDecl(C, RD, KmpInt32Ty);
2499 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002500 RD->completeDefinition();
2501 return RD;
2502}
2503
2504static RecordDecl *
2505createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002506 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002507 auto &C = CGM.getContext();
2508 // Build struct kmp_task_t_with_privates {
2509 // kmp_task_t task_data;
2510 // .kmp_privates_t. privates;
2511 // };
2512 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
2513 RD->startDefinition();
2514 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002515 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
2516 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
2517 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002518 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002519 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002520}
2521
2522/// \brief Emit a proxy function which accepts kmp_task_t as the second
2523/// argument.
2524/// \code
2525/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002526/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
2527/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002528/// return 0;
2529/// }
2530/// \endcode
2531static llvm::Value *
2532emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002533 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
2534 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002535 QualType SharedsPtrTy, llvm::Value *TaskFunction,
2536 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002537 auto &C = CGM.getContext();
2538 FunctionArgList Args;
2539 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2540 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002541 /*Id=*/nullptr,
2542 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002543 Args.push_back(&GtidArg);
2544 Args.push_back(&TaskTypeArg);
2545 FunctionType::ExtInfo Info;
2546 auto &TaskEntryFnInfo =
2547 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2548 /*isVariadic=*/false);
2549 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
2550 auto *TaskEntry =
2551 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
2552 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002553 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002554 CodeGenFunction CGF(CGM);
2555 CGF.disableDebugInfo();
2556 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
2557
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002558 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
2559 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002560 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002561 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002562 LValue TDBase = CGF.EmitLoadOfPointerLValue(
2563 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2564 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002565 auto *KmpTaskTWithPrivatesQTyRD =
2566 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002567 LValue Base =
2568 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002569 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
2570 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
2571 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
2572 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
2573
2574 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
2575 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002576 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002577 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002578 CGF.ConvertTypeForMem(SharedsPtrTy));
2579
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002580 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
2581 llvm::Value *PrivatesParam;
2582 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
2583 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
2584 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002585 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002586 } else {
2587 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2588 }
2589
2590 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
2591 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002592 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
2593 CGF.EmitStoreThroughLValue(
2594 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00002595 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002596 CGF.FinishFunction();
2597 return TaskEntry;
2598}
2599
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002600static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
2601 SourceLocation Loc,
2602 QualType KmpInt32Ty,
2603 QualType KmpTaskTWithPrivatesPtrQTy,
2604 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002605 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002606 FunctionArgList Args;
2607 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2608 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002609 /*Id=*/nullptr,
2610 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002611 Args.push_back(&GtidArg);
2612 Args.push_back(&TaskTypeArg);
2613 FunctionType::ExtInfo Info;
2614 auto &DestructorFnInfo =
2615 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
2616 /*isVariadic=*/false);
2617 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
2618 auto *DestructorFn =
2619 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
2620 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002621 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
2622 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002623 CodeGenFunction CGF(CGM);
2624 CGF.disableDebugInfo();
2625 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
2626 Args);
2627
Alexey Bataev31300ed2016-02-04 11:27:03 +00002628 LValue Base = CGF.EmitLoadOfPointerLValue(
2629 CGF.GetAddrOfLocalVar(&TaskTypeArg),
2630 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002631 auto *KmpTaskTWithPrivatesQTyRD =
2632 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
2633 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002634 Base = CGF.EmitLValueForField(Base, *FI);
2635 for (auto *Field :
2636 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
2637 if (auto DtorKind = Field->getType().isDestructedType()) {
2638 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
2639 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
2640 }
2641 }
2642 CGF.FinishFunction();
2643 return DestructorFn;
2644}
2645
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002646/// \brief Emit a privates mapping function for correct handling of private and
2647/// firstprivate variables.
2648/// \code
2649/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
2650/// **noalias priv1,..., <tyn> **noalias privn) {
2651/// *priv1 = &.privates.priv1;
2652/// ...;
2653/// *privn = &.privates.privn;
2654/// }
2655/// \endcode
2656static llvm::Value *
2657emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00002658 ArrayRef<const Expr *> PrivateVars,
2659 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002660 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00002661 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002662 auto &C = CGM.getContext();
2663 FunctionArgList Args;
2664 ImplicitParamDecl TaskPrivatesArg(
2665 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2666 C.getPointerType(PrivatesQTy).withConst().withRestrict());
2667 Args.push_back(&TaskPrivatesArg);
2668 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
2669 unsigned Counter = 1;
2670 for (auto *E: PrivateVars) {
2671 Args.push_back(ImplicitParamDecl::Create(
2672 C, /*DC=*/nullptr, Loc,
2673 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2674 .withConst()
2675 .withRestrict()));
2676 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2677 PrivateVarsPos[VD] = Counter;
2678 ++Counter;
2679 }
2680 for (auto *E : FirstprivateVars) {
2681 Args.push_back(ImplicitParamDecl::Create(
2682 C, /*DC=*/nullptr, Loc,
2683 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
2684 .withConst()
2685 .withRestrict()));
2686 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2687 PrivateVarsPos[VD] = Counter;
2688 ++Counter;
2689 }
2690 FunctionType::ExtInfo Info;
2691 auto &TaskPrivatesMapFnInfo =
2692 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
2693 /*isVariadic=*/false);
2694 auto *TaskPrivatesMapTy =
2695 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
2696 auto *TaskPrivatesMap = llvm::Function::Create(
2697 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
2698 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002699 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
2700 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00002701 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002702 CodeGenFunction CGF(CGM);
2703 CGF.disableDebugInfo();
2704 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
2705 TaskPrivatesMapFnInfo, Args);
2706
2707 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00002708 LValue Base = CGF.EmitLoadOfPointerLValue(
2709 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
2710 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002711 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
2712 Counter = 0;
2713 for (auto *Field : PrivatesQTyRD->fields()) {
2714 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
2715 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00002716 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00002717 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
2718 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002719 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002720 ++Counter;
2721 }
2722 CGF.FinishFunction();
2723 return TaskPrivatesMap;
2724}
2725
Alexey Bataev9e034042015-05-05 04:05:12 +00002726static int array_pod_sort_comparator(const PrivateDataTy *P1,
2727 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002728 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
2729}
2730
2731void CGOpenMPRuntime::emitTaskCall(
2732 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
2733 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
John McCall7f416cc2015-09-08 08:05:57 +00002734 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002735 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
2736 ArrayRef<const Expr *> PrivateCopies,
2737 ArrayRef<const Expr *> FirstprivateVars,
2738 ArrayRef<const Expr *> FirstprivateCopies,
2739 ArrayRef<const Expr *> FirstprivateInits,
2740 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002741 if (!CGF.HaveInsertPoint())
2742 return;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002743 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00002744 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002745 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00002746 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002747 for (auto *E : PrivateVars) {
2748 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2749 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00002750 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00002751 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2752 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002753 ++I;
2754 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002755 I = FirstprivateCopies.begin();
2756 auto IElemInitRef = FirstprivateInits.begin();
2757 for (auto *E : FirstprivateVars) {
2758 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2759 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00002760 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00002761 PrivateHelpersTy(
2762 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2763 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
2764 ++I, ++IElemInitRef;
2765 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002766 llvm::array_pod_sort(Privates.begin(), Privates.end(),
2767 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002768 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2769 // Build type kmp_routine_entry_t (if not built yet).
2770 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002771 // Build type kmp_task_t (if not built yet).
2772 if (KmpTaskTQTy.isNull()) {
2773 KmpTaskTQTy = C.getRecordType(
2774 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
2775 }
2776 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002777 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002778 auto *KmpTaskTWithPrivatesQTyRD =
2779 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
2780 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
2781 QualType KmpTaskTWithPrivatesPtrQTy =
2782 C.getPointerType(KmpTaskTWithPrivatesQTy);
2783 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
2784 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00002785 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002786 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
2787
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002788 // Emit initial values for private copies (if any).
2789 llvm::Value *TaskPrivatesMap = nullptr;
2790 auto *TaskPrivatesMapTy =
2791 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
2792 3)
2793 ->getType();
2794 if (!Privates.empty()) {
2795 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2796 TaskPrivatesMap = emitTaskPrivateMappingFunction(
2797 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
2798 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2799 TaskPrivatesMap, TaskPrivatesMapTy);
2800 } else {
2801 TaskPrivatesMap = llvm::ConstantPointerNull::get(
2802 cast<llvm::PointerType>(TaskPrivatesMapTy));
2803 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002804 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
2805 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002806 auto *TaskEntry = emitProxyTaskFunction(
2807 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002808 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002809
2810 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
2811 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2812 // kmp_routine_entry_t *task_entry);
2813 // Task flags. Format is taken from
2814 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
2815 // description of kmp_tasking_flags struct.
2816 const unsigned TiedFlag = 0x1;
2817 const unsigned FinalFlag = 0x2;
2818 unsigned Flags = Tied ? TiedFlag : 0;
2819 auto *TaskFlags =
2820 Final.getPointer()
2821 ? CGF.Builder.CreateSelect(Final.getPointer(),
2822 CGF.Builder.getInt32(FinalFlag),
2823 CGF.Builder.getInt32(/*C=*/0))
2824 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
2825 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00002826 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002827 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
2828 getThreadID(CGF, Loc), TaskFlags,
2829 KmpTaskTWithPrivatesTySize, SharedsSize,
2830 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2831 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002832 auto *NewTask = CGF.EmitRuntimeCall(
2833 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002834 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2835 NewTask, KmpTaskTWithPrivatesPtrTy);
2836 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
2837 KmpTaskTWithPrivatesQTy);
2838 LValue TDBase =
2839 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002840 // Fill the data in the resulting kmp_task_t record.
2841 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00002842 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002843 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002844 KmpTaskSharedsPtr =
2845 Address(CGF.EmitLoadOfScalar(
2846 CGF.EmitLValueForField(
2847 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
2848 KmpTaskTShareds)),
2849 Loc),
2850 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002851 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002852 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002853 // Emit initial values for private copies (if any).
2854 bool NeedsCleanup = false;
2855 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002856 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2857 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002858 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002859 LValue SharedsBase;
2860 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00002861 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002862 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2863 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
2864 SharedsTy);
2865 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002866 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
2867 cast<CapturedStmt>(*D.getAssociatedStmt()));
2868 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002869 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002870 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002871 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002872 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002873 if (auto *Elem = Pair.second.PrivateElemInit) {
2874 auto *OriginalVD = Pair.second.Original;
2875 auto *SharedField = CapturesInfo.lookup(OriginalVD);
2876 auto SharedRefLValue =
2877 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002878 SharedRefLValue = CGF.MakeAddrLValue(
2879 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
2880 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002881 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002882 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002883 // Initialize firstprivate array.
2884 if (!isa<CXXConstructExpr>(Init) ||
2885 CGF.isTrivialInitializer(Init)) {
2886 // Perform simple memcpy.
2887 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002888 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00002889 } else {
2890 // Initialize firstprivate array using element-by-element
2891 // intialization.
2892 CGF.EmitOMPAggregateAssign(
2893 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002894 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00002895 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002896 // Clean up any temporaries needed by the initialization.
2897 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002898 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002899 return SrcElement;
2900 });
2901 (void)InitScope.Privatize();
2902 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00002903 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
2904 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002905 CGF.EmitAnyExprToMem(Init, DestElement,
2906 Init->getType().getQualifiers(),
2907 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002908 });
2909 }
2910 } else {
2911 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002912 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00002913 return SharedRefLValue.getAddress();
2914 });
2915 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00002916 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002917 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
2918 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002919 }
2920 } else {
2921 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
2922 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002923 }
2924 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002925 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002926 }
2927 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002928 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002929 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002930 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
2931 KmpTaskTWithPrivatesPtrQTy,
2932 KmpTaskTWithPrivatesQTy)
2933 : llvm::ConstantPointerNull::get(
2934 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
2935 LValue Destructor = CGF.EmitLValueForField(
2936 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
2937 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2938 DestructorFn, KmpRoutineEntryPtrTy),
2939 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002940
2941 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00002942 Address DependenciesArray = Address::invalid();
2943 unsigned NumDependencies = Dependences.size();
2944 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002945 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00002946 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002947 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
2948 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002949 QualType FlagsTy =
2950 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002951 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
2952 if (KmpDependInfoTy.isNull()) {
2953 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
2954 KmpDependInfoRD->startDefinition();
2955 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
2956 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
2957 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
2958 KmpDependInfoRD->completeDefinition();
2959 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
2960 } else {
2961 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
2962 }
John McCall7f416cc2015-09-08 08:05:57 +00002963 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002964 // Define type kmp_depend_info[<Dependences.size()>];
2965 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00002966 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002967 ArrayType::Normal, /*IndexTypeQuals=*/0);
2968 // kmp_depend_info[<Dependences.size()>] deps;
John McCall7f416cc2015-09-08 08:05:57 +00002969 DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
2970 for (unsigned i = 0; i < NumDependencies; ++i) {
2971 const Expr *E = Dependences[i].second;
2972 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002973 llvm::Value *Size;
2974 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002975 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
2976 LValue UpAddrLVal =
2977 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
2978 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00002979 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002980 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00002981 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002982 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
2983 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002984 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00002985 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002986 auto Base = CGF.MakeAddrLValue(
2987 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002988 KmpDependInfoTy);
2989 // deps[i].base_addr = &<Dependences[i].second>;
2990 auto BaseAddrLVal = CGF.EmitLValueForField(
2991 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00002992 CGF.EmitStoreOfScalar(
2993 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
2994 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002995 // deps[i].len = sizeof(<Dependences[i].second>);
2996 auto LenLVal = CGF.EmitLValueForField(
2997 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
2998 CGF.EmitStoreOfScalar(Size, LenLVal);
2999 // deps[i].flags = <Dependences[i].first>;
3000 RTLDependenceKindTy DepKind;
3001 switch (Dependences[i].first) {
3002 case OMPC_DEPEND_in:
3003 DepKind = DepIn;
3004 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003005 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003006 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003007 case OMPC_DEPEND_inout:
3008 DepKind = DepInOut;
3009 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003010 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003011 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003012 case OMPC_DEPEND_unknown:
3013 llvm_unreachable("Unknown task dependence type");
3014 }
3015 auto FlagsLVal = CGF.EmitLValueForField(
3016 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3017 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3018 FlagsLVal);
3019 }
John McCall7f416cc2015-09-08 08:05:57 +00003020 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3021 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003022 CGF.VoidPtrTy);
3023 }
3024
Alexey Bataev62b63b12015-03-10 07:28:44 +00003025 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3026 // libcall.
3027 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
3028 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003029 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3030 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3031 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3032 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003033 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003034 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003035 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3036 llvm::Value *DepTaskArgs[7];
3037 if (NumDependencies) {
3038 DepTaskArgs[0] = UpLoc;
3039 DepTaskArgs[1] = ThreadID;
3040 DepTaskArgs[2] = NewTask;
3041 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3042 DepTaskArgs[4] = DependenciesArray.getPointer();
3043 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3044 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3045 }
3046 auto &&ThenCodeGen = [this, NumDependencies,
3047 &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
3048 // TODO: add check for untied tasks.
3049 if (NumDependencies) {
3050 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
3051 DepTaskArgs);
3052 } else {
3053 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
3054 TaskArgs);
3055 }
Alexey Bataev1d677132015-04-22 13:57:31 +00003056 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003057 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
3058 IfCallEndCleanup;
John McCall7f416cc2015-09-08 08:05:57 +00003059
3060 llvm::Value *DepWaitTaskArgs[6];
3061 if (NumDependencies) {
3062 DepWaitTaskArgs[0] = UpLoc;
3063 DepWaitTaskArgs[1] = ThreadID;
3064 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3065 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3066 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3067 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3068 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003069 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
John McCall7f416cc2015-09-08 08:05:57 +00003070 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003071 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3072 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3073 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3074 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3075 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003076 if (NumDependencies)
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003077 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
3078 DepWaitTaskArgs);
3079 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3080 // kmp_task_t *new_task);
3081 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
3082 TaskArgs);
3083 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3084 // kmp_task_t *new_task);
3085 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
3086 NormalAndEHCleanup,
3087 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
3088 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00003089
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003090 // Call proxy_task_entry(gtid, new_task);
3091 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3092 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3093 };
John McCall7f416cc2015-09-08 08:05:57 +00003094
Alexey Bataev1d677132015-04-22 13:57:31 +00003095 if (IfCond) {
3096 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
3097 } else {
3098 CodeGenFunction::RunCleanupsScope Scope(CGF);
3099 ThenCodeGen(CGF);
3100 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003101}
3102
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003103/// \brief Emit reduction operation for each element of array (required for
3104/// array sections) LHS op = RHS.
3105/// \param Type Type of array.
3106/// \param LHSVar Variable on the left side of the reduction operation
3107/// (references element of array in original variable).
3108/// \param RHSVar Variable on the right side of the reduction operation
3109/// (references element of array in original variable).
3110/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3111/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003112static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003113 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3114 const VarDecl *RHSVar,
3115 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3116 const Expr *, const Expr *)> &RedOpGen,
3117 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3118 const Expr *UpExpr = nullptr) {
3119 // Perform element-by-element initialization.
3120 QualType ElementTy;
3121 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3122 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3123
3124 // Drill down to the base element type on both arrays.
3125 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3126 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3127
3128 auto RHSBegin = RHSAddr.getPointer();
3129 auto LHSBegin = LHSAddr.getPointer();
3130 // Cast from pointer to array type to pointer to single element.
3131 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3132 // The basic structure here is a while-do loop.
3133 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3134 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3135 auto IsEmpty =
3136 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3137 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3138
3139 // Enter the loop body, making that address the current address.
3140 auto EntryBB = CGF.Builder.GetInsertBlock();
3141 CGF.EmitBlock(BodyBB);
3142
3143 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3144
3145 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3146 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3147 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3148 Address RHSElementCurrent =
3149 Address(RHSElementPHI,
3150 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3151
3152 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3153 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3154 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3155 Address LHSElementCurrent =
3156 Address(LHSElementPHI,
3157 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3158
3159 // Emit copy.
3160 CodeGenFunction::OMPPrivateScope Scope(CGF);
3161 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3162 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3163 Scope.Privatize();
3164 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3165 Scope.ForceCleanup();
3166
3167 // Shift the address forward by one element.
3168 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3169 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3170 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3171 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3172 // Check whether we've reached the end.
3173 auto Done =
3174 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3175 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3176 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3177 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3178
3179 // Done.
3180 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3181}
3182
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003183static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3184 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003185 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003186 ArrayRef<const Expr *> LHSExprs,
3187 ArrayRef<const Expr *> RHSExprs,
3188 ArrayRef<const Expr *> ReductionOps) {
3189 auto &C = CGM.getContext();
3190
3191 // void reduction_func(void *LHSArg, void *RHSArg);
3192 FunctionArgList Args;
3193 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3194 C.VoidPtrTy);
3195 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3196 C.VoidPtrTy);
3197 Args.push_back(&LHSArg);
3198 Args.push_back(&RHSArg);
3199 FunctionType::ExtInfo EI;
3200 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
3201 C.VoidTy, Args, EI, /*isVariadic=*/false);
3202 auto *Fn = llvm::Function::Create(
3203 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3204 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003205 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003206 CodeGenFunction CGF(CGM);
3207 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3208
3209 // Dst = (void*[n])(LHSArg);
3210 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003211 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3212 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3213 ArgsType), CGF.getPointerAlign());
3214 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3215 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3216 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003217
3218 // ...
3219 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3220 // ...
3221 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003222 auto IPriv = Privates.begin();
3223 unsigned Idx = 0;
3224 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003225 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3226 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003227 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003228 });
3229 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3230 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003231 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003232 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003233 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003234 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003235 // Get array size and emit VLA type.
3236 ++Idx;
3237 Address Elem =
3238 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3239 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003240 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3241 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003242 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00003243 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003244 CGF.EmitVariablyModifiedType(PrivTy);
3245 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003246 }
3247 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003248 IPriv = Privates.begin();
3249 auto ILHS = LHSExprs.begin();
3250 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003251 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003252 if ((*IPriv)->getType()->isArrayType()) {
3253 // Emit reduction for array section.
3254 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3255 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3256 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3257 [=](CodeGenFunction &CGF, const Expr *,
3258 const Expr *,
3259 const Expr *) { CGF.EmitIgnoredExpr(E); });
3260 } else
3261 // Emit reduction for array subscript or single variable.
3262 CGF.EmitIgnoredExpr(E);
3263 ++IPriv, ++ILHS, ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003264 }
3265 Scope.ForceCleanup();
3266 CGF.FinishFunction();
3267 return Fn;
3268}
3269
3270void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003271 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003272 ArrayRef<const Expr *> LHSExprs,
3273 ArrayRef<const Expr *> RHSExprs,
3274 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003275 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003276 if (!CGF.HaveInsertPoint())
3277 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003278 // Next code should be emitted for reduction:
3279 //
3280 // static kmp_critical_name lock = { 0 };
3281 //
3282 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
3283 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
3284 // ...
3285 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
3286 // *(Type<n>-1*)rhs[<n>-1]);
3287 // }
3288 //
3289 // ...
3290 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
3291 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3292 // RedList, reduce_func, &<lock>)) {
3293 // case 1:
3294 // ...
3295 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3296 // ...
3297 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3298 // break;
3299 // case 2:
3300 // ...
3301 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3302 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00003303 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003304 // break;
3305 // default:;
3306 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003307 //
3308 // if SimpleReduction is true, only the next code is generated:
3309 // ...
3310 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3311 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003312
3313 auto &C = CGM.getContext();
3314
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003315 if (SimpleReduction) {
3316 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003317 auto IPriv = Privates.begin();
3318 auto ILHS = LHSExprs.begin();
3319 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003320 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003321 if ((*IPriv)->getType()->isArrayType()) {
3322 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3323 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3324 EmitOMPAggregateReduction(
3325 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3326 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3327 const Expr *) { CGF.EmitIgnoredExpr(E); });
3328 } else
3329 CGF.EmitIgnoredExpr(E);
3330 ++IPriv, ++ILHS, ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00003331 }
3332 return;
3333 }
3334
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003335 // 1. Build a list of reduction variables.
3336 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003337 auto Size = RHSExprs.size();
3338 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00003339 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003340 // Reserve place for array size.
3341 ++Size;
3342 }
3343 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003344 QualType ReductionArrayTy =
3345 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3346 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00003347 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003348 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003349 auto IPriv = Privates.begin();
3350 unsigned Idx = 0;
3351 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003352 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003353 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003354 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003355 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003356 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3357 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003358 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003359 // Store array size.
3360 ++Idx;
3361 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3362 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003363 llvm::Value *Size = CGF.Builder.CreateIntCast(
3364 CGF.getVLASize(
3365 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3366 .first,
3367 CGF.SizeTy, /*isSigned=*/false);
3368 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3369 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003370 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003371 }
3372
3373 // 2. Emit reduce_func().
3374 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003375 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3376 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003377
3378 // 3. Create static kmp_critical_name lock = { 0 };
3379 auto *Lock = getCriticalRegionLock(".reduction");
3380
3381 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3382 // RedList, reduce_func, &<lock>);
3383 auto *IdentTLoc = emitUpdateLocation(
3384 CGF, Loc,
3385 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
3386 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003387 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003388 auto *RL =
3389 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
3390 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003391 llvm::Value *Args[] = {
3392 IdentTLoc, // ident_t *<loc>
3393 ThreadId, // i32 <gtid>
3394 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
3395 ReductionArrayTySize, // size_type sizeof(RedList)
3396 RL, // void *RedList
3397 ReductionFn, // void (*) (void *, void *) <reduce_func>
3398 Lock // kmp_critical_name *&<lock>
3399 };
3400 auto Res = CGF.EmitRuntimeCall(
3401 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
3402 : OMPRTL__kmpc_reduce),
3403 Args);
3404
3405 // 5. Build switch(res)
3406 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3407 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
3408
3409 // 6. Build case 1:
3410 // ...
3411 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3412 // ...
3413 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3414 // break;
3415 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
3416 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3417 CGF.EmitBlock(Case1BB);
3418
3419 {
3420 CodeGenFunction::RunCleanupsScope Scope(CGF);
3421 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3422 llvm::Value *EndArgs[] = {
3423 IdentTLoc, // ident_t *<loc>
3424 ThreadId, // i32 <gtid>
3425 Lock // kmp_critical_name *&<lock>
3426 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00003427 CGF.EHStack
3428 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3429 NormalAndEHCleanup,
3430 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
3431 : OMPRTL__kmpc_end_reduce),
3432 llvm::makeArrayRef(EndArgs));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003433 auto IPriv = Privates.begin();
3434 auto ILHS = LHSExprs.begin();
3435 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003436 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003437 if ((*IPriv)->getType()->isArrayType()) {
3438 // Emit reduction for array section.
3439 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3440 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3441 EmitOMPAggregateReduction(
3442 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3443 [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3444 const Expr *) { CGF.EmitIgnoredExpr(E); });
3445 } else
3446 // Emit reduction for array subscript or single variable.
3447 CGF.EmitIgnoredExpr(E);
3448 ++IPriv, ++ILHS, ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003449 }
3450 }
3451
3452 CGF.EmitBranch(DefaultBB);
3453
3454 // 7. Build case 2:
3455 // ...
3456 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3457 // ...
3458 // break;
3459 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
3460 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
3461 CGF.EmitBlock(Case2BB);
3462
3463 {
3464 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00003465 if (!WithNowait) {
3466 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
3467 llvm::Value *EndArgs[] = {
3468 IdentTLoc, // ident_t *<loc>
3469 ThreadId, // i32 <gtid>
3470 Lock // kmp_critical_name *&<lock>
3471 };
3472 CGF.EHStack
3473 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3474 NormalAndEHCleanup,
3475 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
3476 llvm::makeArrayRef(EndArgs));
3477 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003478 auto ILHS = LHSExprs.begin();
3479 auto IRHS = RHSExprs.begin();
3480 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003481 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003482 const Expr *XExpr = nullptr;
3483 const Expr *EExpr = nullptr;
3484 const Expr *UpExpr = nullptr;
3485 BinaryOperatorKind BO = BO_Comma;
3486 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
3487 if (BO->getOpcode() == BO_Assign) {
3488 XExpr = BO->getLHS();
3489 UpExpr = BO->getRHS();
3490 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003491 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003492 // Try to emit update expression as a simple atomic.
3493 auto *RHSExpr = UpExpr;
3494 if (RHSExpr) {
3495 // Analyze RHS part of the whole expression.
3496 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
3497 RHSExpr->IgnoreParenImpCasts())) {
3498 // If this is a conditional operator, analyze its condition for
3499 // min/max reduction operator.
3500 RHSExpr = ACO->getCond();
3501 }
3502 if (auto *BORHS =
3503 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
3504 EExpr = BORHS->getRHS();
3505 BO = BORHS->getOpcode();
3506 }
Alexey Bataev69a47792015-05-07 03:54:03 +00003507 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003508 if (XExpr) {
3509 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3510 auto &&AtomicRedGen = [this, BO, VD, IPriv,
3511 Loc](CodeGenFunction &CGF, const Expr *XExpr,
3512 const Expr *EExpr, const Expr *UpExpr) {
3513 LValue X = CGF.EmitLValue(XExpr);
3514 RValue E;
3515 if (EExpr)
3516 E = CGF.EmitAnyExpr(EExpr);
3517 CGF.EmitOMPAtomicSimpleUpdateExpr(
3518 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
Alexey Bataev8524d152016-01-21 12:35:58 +00003519 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003520 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataev8524d152016-01-21 12:35:58 +00003521 PrivateScope.addPrivate(
3522 VD, [&CGF, VD, XRValue, Loc]() -> Address {
3523 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
3524 CGF.emitOMPSimpleStore(
3525 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
3526 VD->getType().getNonReferenceType(), Loc);
3527 return LHSTemp;
3528 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003529 (void)PrivateScope.Privatize();
3530 return CGF.EmitAnyExpr(UpExpr);
3531 });
3532 };
3533 if ((*IPriv)->getType()->isArrayType()) {
3534 // Emit atomic reduction for array section.
3535 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3536 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
3537 AtomicRedGen, XExpr, EExpr, UpExpr);
3538 } else
3539 // Emit atomic reduction for array subscript or single variable.
3540 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
3541 } else {
3542 // Emit as a critical region.
3543 auto &&CritRedGen = [this, E, Loc](CodeGenFunction &CGF, const Expr *,
3544 const Expr *, const Expr *) {
3545 emitCriticalRegion(
3546 CGF, ".atomic_reduction",
3547 [E](CodeGenFunction &CGF) { CGF.EmitIgnoredExpr(E); }, Loc);
3548 };
3549 if ((*IPriv)->getType()->isArrayType()) {
3550 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3551 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3552 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3553 CritRedGen);
3554 } else
3555 CritRedGen(CGF, nullptr, nullptr, nullptr);
3556 }
3557 ++ILHS, ++IRHS, ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003558 }
3559 }
3560
3561 CGF.EmitBranch(DefaultBB);
3562 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3563}
3564
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003565void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
3566 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003567 if (!CGF.HaveInsertPoint())
3568 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00003569 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
3570 // global_tid);
3571 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3572 // Ignore return result until untied tasks are supported.
3573 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
3574}
3575
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003576void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003577 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003578 const RegionCodeGenTy &CodeGen,
3579 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003580 if (!CGF.HaveInsertPoint())
3581 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003582 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003583 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00003584}
3585
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003586namespace {
3587enum RTCancelKind {
3588 CancelNoreq = 0,
3589 CancelParallel = 1,
3590 CancelLoop = 2,
3591 CancelSections = 3,
3592 CancelTaskgroup = 4
3593};
3594}
3595
3596static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
3597 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00003598 if (CancelRegion == OMPD_parallel)
3599 CancelKind = CancelParallel;
3600 else if (CancelRegion == OMPD_for)
3601 CancelKind = CancelLoop;
3602 else if (CancelRegion == OMPD_sections)
3603 CancelKind = CancelSections;
3604 else {
3605 assert(CancelRegion == OMPD_taskgroup);
3606 CancelKind = CancelTaskgroup;
3607 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003608 return CancelKind;
3609}
3610
3611void CGOpenMPRuntime::emitCancellationPointCall(
3612 CodeGenFunction &CGF, SourceLocation Loc,
3613 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003614 if (!CGF.HaveInsertPoint())
3615 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003616 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
3617 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003618 if (auto *OMPRegionInfo =
3619 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003620 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003621 llvm::Value *Args[] = {
3622 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3623 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003624 // Ignore return result until untied tasks are supported.
3625 auto *Result = CGF.EmitRuntimeCall(
3626 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
3627 // if (__kmpc_cancellationpoint()) {
3628 // __kmpc_cancel_barrier();
3629 // exit from construct;
3630 // }
3631 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3632 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3633 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3634 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3635 CGF.EmitBlock(ExitBB);
3636 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00003637 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003638 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003639 auto CancelDest =
3640 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003641 CGF.EmitBranchThroughCleanup(CancelDest);
3642 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3643 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00003644 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00003645}
3646
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003647void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00003648 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003649 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003650 if (!CGF.HaveInsertPoint())
3651 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003652 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
3653 // kmp_int32 cncl_kind);
3654 if (auto *OMPRegionInfo =
3655 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev87933c72015-09-18 08:07:34 +00003656 auto &&ThenGen = [this, Loc, CancelRegion,
3657 OMPRegionInfo](CodeGenFunction &CGF) {
3658 llvm::Value *Args[] = {
3659 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3660 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
3661 // Ignore return result until untied tasks are supported.
3662 auto *Result =
3663 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
3664 // if (__kmpc_cancel()) {
3665 // __kmpc_cancel_barrier();
3666 // exit from construct;
3667 // }
3668 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3669 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3670 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3671 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3672 CGF.EmitBlock(ExitBB);
3673 // __kmpc_cancel_barrier();
3674 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
3675 // exit from construct;
3676 auto CancelDest =
3677 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
3678 CGF.EmitBranchThroughCleanup(CancelDest);
3679 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3680 };
3681 if (IfCond)
3682 emitOMPIfClause(CGF, IfCond, ThenGen, [](CodeGenFunction &) {});
3683 else
3684 ThenGen(CGF);
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00003685 }
3686}
Samuel Antaobed3c462015-10-02 16:14:20 +00003687
Samuel Antaoee8fb302016-01-06 13:42:12 +00003688/// \brief Obtain information that uniquely identifies a target entry. This
3689/// consists of the file and device IDs as well as line and column numbers
3690/// associated with the relevant entry source location.
3691static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
3692 unsigned &DeviceID, unsigned &FileID,
3693 unsigned &LineNum, unsigned &ColumnNum) {
3694
3695 auto &SM = C.getSourceManager();
3696
3697 // The loc should be always valid and have a file ID (the user cannot use
3698 // #pragma directives in macros)
3699
3700 assert(Loc.isValid() && "Source location is expected to be always valid.");
3701 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
3702
3703 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3704 assert(PLoc.isValid() && "Source location is expected to be always valid.");
3705
3706 llvm::sys::fs::UniqueID ID;
3707 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
3708 llvm_unreachable("Source file with target region no longer exists!");
3709
3710 DeviceID = ID.getDevice();
3711 FileID = ID.getFile();
3712 LineNum = PLoc.getLine();
3713 ColumnNum = PLoc.getColumn();
3714 return;
3715}
3716
3717void CGOpenMPRuntime::emitTargetOutlinedFunction(
3718 const OMPExecutableDirective &D, StringRef ParentName,
3719 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
3720 bool IsOffloadEntry) {
3721
3722 assert(!ParentName.empty() && "Invalid target region parent name!");
3723
Samuel Antaobed3c462015-10-02 16:14:20 +00003724 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
3725
Samuel Antaoee8fb302016-01-06 13:42:12 +00003726 // Emit target region as a standalone region.
3727 auto &&CodeGen = [&CS](CodeGenFunction &CGF) {
3728 CGF.EmitStmt(CS.getCapturedStmt());
3729 };
3730
3731 // Create a unique name for the proxy/entry function that using the source
3732 // location information of the current target region. The name will be
3733 // something like:
3734 //
3735 // .omp_offloading.DD_FFFF.PP.lBB.cCC
3736 //
3737 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
3738 // mangled name of the function that encloses the target region, BB is the
3739 // line number of the target region, and CC is the column number of the target
3740 // region.
3741
3742 unsigned DeviceID;
3743 unsigned FileID;
3744 unsigned Line;
3745 unsigned Column;
3746 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
3747 Line, Column);
3748 SmallString<64> EntryFnName;
3749 {
3750 llvm::raw_svector_ostream OS(EntryFnName);
3751 OS << ".omp_offloading" << llvm::format(".%x", DeviceID)
3752 << llvm::format(".%x.", FileID) << ParentName << ".l" << Line << ".c"
3753 << Column;
3754 }
3755
Samuel Antaobed3c462015-10-02 16:14:20 +00003756 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003757 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00003758 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003759
3760 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
3761
3762 // If this target outline function is not an offload entry, we don't need to
3763 // register it.
3764 if (!IsOffloadEntry)
3765 return;
3766
3767 // The target region ID is used by the runtime library to identify the current
3768 // target region, so it only has to be unique and not necessarily point to
3769 // anything. It could be the pointer to the outlined function that implements
3770 // the target region, but we aren't using that so that the compiler doesn't
3771 // need to keep that, and could therefore inline the host function if proven
3772 // worthwhile during optimization. In the other hand, if emitting code for the
3773 // device, the ID has to be the function address so that it can retrieved from
3774 // the offloading entry and launched by the runtime library. We also mark the
3775 // outlined function to have external linkage in case we are emitting code for
3776 // the device, because these functions will be entry points to the device.
3777
3778 if (CGM.getLangOpts().OpenMPIsDevice) {
3779 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
3780 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
3781 } else
3782 OutlinedFnID = new llvm::GlobalVariable(
3783 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
3784 llvm::GlobalValue::PrivateLinkage,
3785 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
3786
3787 // Register the information for the entry associated with this target region.
3788 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
3789 DeviceID, FileID, ParentName, Line, Column, OutlinedFn, OutlinedFnID);
3790 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00003791}
3792
3793void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
3794 const OMPExecutableDirective &D,
3795 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003796 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00003797 const Expr *IfCond, const Expr *Device,
3798 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003799 if (!CGF.HaveInsertPoint())
3800 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00003801 /// \brief Values for bit flags used to specify the mapping type for
3802 /// offloading.
3803 enum OpenMPOffloadMappingFlags {
3804 /// \brief Allocate memory on the device and move data from host to device.
3805 OMP_MAP_TO = 0x01,
3806 /// \brief Allocate memory on the device and move data from device to host.
3807 OMP_MAP_FROM = 0x02,
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003808 /// \brief The element passed to the device is a pointer.
3809 OMP_MAP_PTR = 0x20,
3810 /// \brief Pass the element to the device by value.
3811 OMP_MAP_BYCOPY = 0x80,
Samuel Antaobed3c462015-10-02 16:14:20 +00003812 };
3813
3814 enum OpenMPOffloadingReservedDeviceIDs {
3815 /// \brief Device ID if the device was not defined, runtime should get it
3816 /// from environment variables in the spec.
3817 OMP_DEVICEID_UNDEF = -1,
3818 };
3819
Samuel Antaoee8fb302016-01-06 13:42:12 +00003820 assert(OutlinedFn && "Invalid outlined function!");
3821
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003822 auto &Ctx = CGF.getContext();
3823
Samuel Antaobed3c462015-10-02 16:14:20 +00003824 // Fill up the arrays with the all the captured variables.
3825 SmallVector<llvm::Value *, 16> BasePointers;
3826 SmallVector<llvm::Value *, 16> Pointers;
3827 SmallVector<llvm::Value *, 16> Sizes;
3828 SmallVector<unsigned, 16> MapTypes;
3829
3830 bool hasVLACaptures = false;
3831
3832 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
3833 auto RI = CS.getCapturedRecordDecl()->field_begin();
3834 // auto II = CS.capture_init_begin();
3835 auto CV = CapturedVars.begin();
3836 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
3837 CE = CS.capture_end();
3838 CI != CE; ++CI, ++RI, ++CV) {
3839 StringRef Name;
3840 QualType Ty;
3841 llvm::Value *BasePointer;
3842 llvm::Value *Pointer;
3843 llvm::Value *Size;
3844 unsigned MapType;
3845
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003846 // VLA sizes are passed to the outlined region by copy.
Samuel Antaobed3c462015-10-02 16:14:20 +00003847 if (CI->capturesVariableArrayType()) {
3848 BasePointer = Pointer = *CV;
Alexey Bataev1189bd02016-01-26 12:20:39 +00003849 Size = CGF.getTypeSize(RI->getType());
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003850 // Copy to the device as an argument. No need to retrieve it.
3851 MapType = OMP_MAP_BYCOPY;
Samuel Antaobed3c462015-10-02 16:14:20 +00003852 hasVLACaptures = true;
Samuel Antaobed3c462015-10-02 16:14:20 +00003853 } else if (CI->capturesThis()) {
3854 BasePointer = Pointer = *CV;
3855 const PointerType *PtrTy = cast<PointerType>(RI->getType().getTypePtr());
Alexey Bataev1189bd02016-01-26 12:20:39 +00003856 Size = CGF.getTypeSize(PtrTy->getPointeeType());
Samuel Antaobed3c462015-10-02 16:14:20 +00003857 // Default map type.
3858 MapType = OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003859 } else if (CI->capturesVariableByCopy()) {
3860 MapType = OMP_MAP_BYCOPY;
3861 if (!RI->getType()->isAnyPointerType()) {
3862 // If the field is not a pointer, we need to save the actual value and
3863 // load it as a void pointer.
3864 auto DstAddr = CGF.CreateMemTemp(
3865 Ctx.getUIntPtrType(),
3866 Twine(CI->getCapturedVar()->getName()) + ".casted");
3867 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
3868
3869 auto *SrcAddrVal = CGF.EmitScalarConversion(
3870 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
3871 Ctx.getPointerType(RI->getType()), SourceLocation());
3872 LValue SrcLV =
3873 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
3874
3875 // Store the value using the source type pointer.
3876 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
3877
3878 // Load the value using the destination type pointer.
3879 BasePointer = Pointer =
3880 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
3881 } else {
3882 MapType |= OMP_MAP_PTR;
3883 BasePointer = Pointer = *CV;
3884 }
Alexey Bataev1189bd02016-01-26 12:20:39 +00003885 Size = CGF.getTypeSize(RI->getType());
Samuel Antaobed3c462015-10-02 16:14:20 +00003886 } else {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003887 assert(CI->capturesVariable() && "Expected captured reference.");
Samuel Antaobed3c462015-10-02 16:14:20 +00003888 BasePointer = Pointer = *CV;
3889
3890 const ReferenceType *PtrTy =
3891 cast<ReferenceType>(RI->getType().getTypePtr());
3892 QualType ElementType = PtrTy->getPointeeType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003893 Size = CGF.getTypeSize(ElementType);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003894 // The default map type for a scalar/complex type is 'to' because by
3895 // default the value doesn't have to be retrieved. For an aggregate type,
3896 // the default is 'tofrom'.
3897 MapType = ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
3898 : OMP_MAP_TO;
3899 if (ElementType->isAnyPointerType())
3900 MapType |= OMP_MAP_PTR;
Samuel Antaobed3c462015-10-02 16:14:20 +00003901 }
3902
3903 BasePointers.push_back(BasePointer);
3904 Pointers.push_back(Pointer);
3905 Sizes.push_back(Size);
3906 MapTypes.push_back(MapType);
3907 }
3908
3909 // Keep track on whether the host function has to be executed.
3910 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003911 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00003912 auto OffloadError = CGF.MakeAddrLValue(
3913 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
3914 OffloadErrorQType);
3915 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
3916 OffloadError);
3917
3918 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003919 auto &&ThenGen = [this, &Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003920 hasVLACaptures, Device, OutlinedFnID, OffloadError,
Samuel Antaobed3c462015-10-02 16:14:20 +00003921 OffloadErrorQType](CodeGenFunction &CGF) {
3922 unsigned PointerNumVal = BasePointers.size();
3923 llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
3924 llvm::Value *BasePointersArray;
3925 llvm::Value *PointersArray;
3926 llvm::Value *SizesArray;
3927 llvm::Value *MapTypesArray;
3928
3929 if (PointerNumVal) {
3930 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003931 QualType PointerArrayType = Ctx.getConstantArrayType(
3932 Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00003933 /*IndexTypeQuals=*/0);
3934
3935 BasePointersArray =
3936 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
3937 PointersArray =
3938 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
3939
3940 // If we don't have any VLA types, we can use a constant array for the map
3941 // sizes, otherwise we need to fill up the arrays as we do for the
3942 // pointers.
3943 if (hasVLACaptures) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003944 QualType SizeArrayType = Ctx.getConstantArrayType(
3945 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00003946 /*IndexTypeQuals=*/0);
3947 SizesArray =
3948 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
3949 } else {
3950 // We expect all the sizes to be constant, so we collect them to create
3951 // a constant array.
3952 SmallVector<llvm::Constant *, 16> ConstSizes;
3953 for (auto S : Sizes)
3954 ConstSizes.push_back(cast<llvm::Constant>(S));
3955
3956 auto *SizesArrayInit = llvm::ConstantArray::get(
3957 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
3958 auto *SizesArrayGbl = new llvm::GlobalVariable(
3959 CGM.getModule(), SizesArrayInit->getType(),
3960 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
3961 SizesArrayInit, ".offload_sizes");
3962 SizesArrayGbl->setUnnamedAddr(true);
3963 SizesArray = SizesArrayGbl;
3964 }
3965
3966 // The map types are always constant so we don't need to generate code to
3967 // fill arrays. Instead, we create an array constant.
3968 llvm::Constant *MapTypesArrayInit =
3969 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
3970 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
3971 CGM.getModule(), MapTypesArrayInit->getType(),
3972 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
3973 MapTypesArrayInit, ".offload_maptypes");
3974 MapTypesArrayGbl->setUnnamedAddr(true);
3975 MapTypesArray = MapTypesArrayGbl;
3976
3977 for (unsigned i = 0; i < PointerNumVal; ++i) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003978
3979 llvm::Value *BPVal = BasePointers[i];
3980 if (BPVal->getType()->isPointerTy())
3981 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
3982 else {
3983 assert(BPVal->getType()->isIntegerTy() &&
3984 "If not a pointer, the value type must be an integer.");
3985 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
3986 }
Samuel Antaobed3c462015-10-02 16:14:20 +00003987 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
3988 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal),
3989 BasePointersArray, 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003990 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
3991 CGF.Builder.CreateStore(BPVal, BPAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00003992
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003993 llvm::Value *PVal = Pointers[i];
3994 if (PVal->getType()->isPointerTy())
3995 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
3996 else {
3997 assert(PVal->getType()->isIntegerTy() &&
3998 "If not a pointer, the value type must be an integer.");
3999 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
4000 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004001 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
4002 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4003 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004004 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4005 CGF.Builder.CreateStore(PVal, PAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00004006
4007 if (hasVLACaptures) {
4008 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
4009 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4010 /*Idx0=*/0,
4011 /*Idx1=*/i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004012 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
Samuel Antaobed3c462015-10-02 16:14:20 +00004013 CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
4014 Sizes[i], CGM.SizeTy, /*isSigned=*/true),
4015 SAddr);
4016 }
4017 }
4018
4019 BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4020 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
4021 /*Idx0=*/0, /*Idx1=*/0);
4022 PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4023 llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4024 /*Idx0=*/0,
4025 /*Idx1=*/0);
4026 SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4027 llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4028 /*Idx0=*/0, /*Idx1=*/0);
4029 MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4030 llvm::ArrayType::get(CGM.Int32Ty, PointerNumVal), MapTypesArray,
4031 /*Idx0=*/0,
4032 /*Idx1=*/0);
4033
4034 } else {
4035 BasePointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4036 PointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4037 SizesArray = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
4038 MapTypesArray =
4039 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
4040 }
4041
4042 // On top of the arrays that were filled up, the target offloading call
4043 // takes as arguments the device id as well as the host pointer. The host
4044 // pointer is used by the runtime library to identify the current target
4045 // region, so it only has to be unique and not necessarily point to
4046 // anything. It could be the pointer to the outlined function that
4047 // implements the target region, but we aren't using that so that the
4048 // compiler doesn't need to keep that, and could therefore inline the host
4049 // function if proven worthwhile during optimization.
4050
Samuel Antaoee8fb302016-01-06 13:42:12 +00004051 // From this point on, we need to have an ID of the target region defined.
4052 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00004053
4054 // Emit device ID if any.
4055 llvm::Value *DeviceID;
4056 if (Device)
4057 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
4058 CGM.Int32Ty, /*isSigned=*/true);
4059 else
4060 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
4061
4062 llvm::Value *OffloadingArgs[] = {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004063 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
4064 PointersArray, SizesArray, MapTypesArray};
Samuel Antaobed3c462015-10-02 16:14:20 +00004065 auto Return = CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target),
4066 OffloadingArgs);
4067
4068 CGF.EmitStoreOfScalar(Return, OffloadError);
4069 };
4070
Samuel Antaoee8fb302016-01-06 13:42:12 +00004071 // Notify that the host version must be executed.
4072 auto &&ElseGen = [this, OffloadError,
4073 OffloadErrorQType](CodeGenFunction &CGF) {
4074 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/-1u),
4075 OffloadError);
4076 };
4077
4078 // If we have a target function ID it means that we need to support
4079 // offloading, otherwise, just execute on the host. We need to execute on host
4080 // regardless of the conditional in the if clause if, e.g., the user do not
4081 // specify target triples.
4082 if (OutlinedFnID) {
4083 if (IfCond) {
4084 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
4085 } else {
4086 CodeGenFunction::RunCleanupsScope Scope(CGF);
4087 ThenGen(CGF);
4088 }
Samuel Antaobed3c462015-10-02 16:14:20 +00004089 } else {
4090 CodeGenFunction::RunCleanupsScope Scope(CGF);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004091 ElseGen(CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00004092 }
4093
4094 // Check the error code and execute the host version if required.
4095 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
4096 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
4097 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
4098 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
4099 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
4100
4101 CGF.EmitBlock(OffloadFailedBlock);
4102 CGF.Builder.CreateCall(OutlinedFn, BasePointers);
4103 CGF.EmitBranch(OffloadContBlock);
4104
4105 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
4106 return;
4107}
Samuel Antaoee8fb302016-01-06 13:42:12 +00004108
4109void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
4110 StringRef ParentName) {
4111 if (!S)
4112 return;
4113
4114 // If we find a OMP target directive, codegen the outline function and
4115 // register the result.
4116 // FIXME: Add other directives with target when they become supported.
4117 bool isTargetDirective = isa<OMPTargetDirective>(S);
4118
4119 if (isTargetDirective) {
4120 auto *E = cast<OMPExecutableDirective>(S);
4121 unsigned DeviceID;
4122 unsigned FileID;
4123 unsigned Line;
4124 unsigned Column;
4125 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
4126 FileID, Line, Column);
4127
4128 // Is this a target region that should not be emitted as an entry point? If
4129 // so just signal we are done with this target region.
4130 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(
4131 DeviceID, FileID, ParentName, Line, Column))
4132 return;
4133
4134 llvm::Function *Fn;
4135 llvm::Constant *Addr;
4136 emitTargetOutlinedFunction(*E, ParentName, Fn, Addr,
4137 /*isOffloadEntry=*/true);
4138 assert(Fn && Addr && "Target region emission failed.");
4139 return;
4140 }
4141
4142 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
4143 if (!E->getAssociatedStmt())
4144 return;
4145
4146 scanForTargetRegionsFunctions(
4147 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
4148 ParentName);
4149 return;
4150 }
4151
4152 // If this is a lambda function, look into its body.
4153 if (auto *L = dyn_cast<LambdaExpr>(S))
4154 S = L->getBody();
4155
4156 // Keep looking for target regions recursively.
4157 for (auto *II : S->children())
4158 scanForTargetRegionsFunctions(II, ParentName);
4159
4160 return;
4161}
4162
4163bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
4164 auto &FD = *cast<FunctionDecl>(GD.getDecl());
4165
4166 // If emitting code for the host, we do not process FD here. Instead we do
4167 // the normal code generation.
4168 if (!CGM.getLangOpts().OpenMPIsDevice)
4169 return false;
4170
4171 // Try to detect target regions in the function.
4172 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
4173
4174 // We should not emit any function othen that the ones created during the
4175 // scanning. Therefore, we signal that this function is completely dealt
4176 // with.
4177 return true;
4178}
4179
4180bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
4181 if (!CGM.getLangOpts().OpenMPIsDevice)
4182 return false;
4183
4184 // Check if there are Ctors/Dtors in this declaration and look for target
4185 // regions in it. We use the complete variant to produce the kernel name
4186 // mangling.
4187 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
4188 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
4189 for (auto *Ctor : RD->ctors()) {
4190 StringRef ParentName =
4191 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
4192 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
4193 }
4194 auto *Dtor = RD->getDestructor();
4195 if (Dtor) {
4196 StringRef ParentName =
4197 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
4198 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
4199 }
4200 }
4201
4202 // If we are in target mode we do not emit any global (declare target is not
4203 // implemented yet). Therefore we signal that GD was processed in this case.
4204 return true;
4205}
4206
4207bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
4208 auto *VD = GD.getDecl();
4209 if (isa<FunctionDecl>(VD))
4210 return emitTargetFunctions(GD);
4211
4212 return emitTargetGlobalVariable(GD);
4213}
4214
4215llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
4216 // If we have offloading in the current module, we need to emit the entries
4217 // now and register the offloading descriptor.
4218 createOffloadEntriesAndInfoMetadata();
4219
4220 // Create and register the offloading binary descriptors. This is the main
4221 // entity that captures all the information about offloading in the current
4222 // compilation unit.
4223 return createOffloadingBinaryDescriptorRegistration();
4224}