blob: fa850155df4f9816f2decb6da7b64dc79277e212 [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"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +000017#include "CGRecordLayout.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000019#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "clang/AST/StmtOpenMP.h"
Richard Smithbf5bcf22018-06-26 23:20:26 +000022#include "clang/Basic/BitmaskEnum.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/ADT/ArrayRef.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000025#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000029#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000030#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000031#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000032
33using namespace clang;
34using namespace CodeGen;
35
Benjamin Kramerc52193f2014-10-10 13:57:57 +000036namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037/// Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000038class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
39public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000040 /// Kinds of OpenMP regions used in codegen.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000041 enum CGOpenMPRegionKind {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// Region with outlined function for standalone 'parallel'
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000043 /// directive.
44 ParallelOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Region with outlined function for standalone 'task' directive.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 TaskOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000047 /// Region for constructs that do not require function outlining,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000048 /// like 'for', 'sections', 'atomic' etc. directives.
49 InlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050 /// Region with outlined function for standalone 'target' directive.
Samuel Antaobed3c462015-10-02 16:14:20 +000051 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 };
Alexey Bataev18095712014-10-10 12:19:54 +000053
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000054 CGOpenMPRegionInfo(const CapturedStmt &CS,
55 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
57 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000060
61 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
63 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000064 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000065 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000067 /// Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000068 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000069 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000072 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000073
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000074 /// Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000075 /// \return LValue for thread id variable. This LValue always has type int32*.
76 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000077
Alexey Bataev48591dd2016-04-20 04:01:36 +000078 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
79
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000080 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000081
Alexey Bataev81c7ea02015-07-03 09:56:58 +000082 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
83
Alexey Bataev25e5b442015-09-15 12:52:43 +000084 bool hasCancel() const { return HasCancel; }
85
Alexey Bataev18095712014-10-10 12:19:54 +000086 static bool classof(const CGCapturedStmtInfo *Info) {
87 return Info->getKind() == CR_OpenMP;
88 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000089
Alexey Bataev48591dd2016-04-20 04:01:36 +000090 ~CGOpenMPRegionInfo() override = default;
91
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000093 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000094 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000095 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000096 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000097};
Alexey Bataev18095712014-10-10 12:19:54 +000098
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000099/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000100class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000102 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000103 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104 OpenMPDirectiveKind Kind, bool HasCancel,
105 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000106 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
107 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000109 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
110 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000112 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000113 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000114 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000115
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000116 /// Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000117 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000118
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000119 static bool classof(const CGCapturedStmtInfo *Info) {
120 return CGOpenMPRegionInfo::classof(Info) &&
121 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
122 ParallelOutlinedRegion;
123 }
124
Alexey Bataev18095712014-10-10 12:19:54 +0000125private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000126 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev18095712014-10-10 12:19:54 +0000127 /// constructs.
128 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000129 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000130};
131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000132/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000134public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000135 class UntiedTaskActionTy final : public PrePostActionTy {
136 bool Untied;
137 const VarDecl *PartIDVar;
138 const RegionCodeGenTy UntiedCodeGen;
139 llvm::SwitchInst *UntiedSwitch = nullptr;
140
141 public:
142 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
143 const RegionCodeGenTy &UntiedCodeGen)
144 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
145 void Enter(CodeGenFunction &CGF) override {
146 if (Untied) {
147 // Emit task switching point.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000148 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000149 CGF.GetAddrOfLocalVar(PartIDVar),
150 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000151 llvm::Value *Res =
152 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
153 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
Alexey Bataev48591dd2016-04-20 04:01:36 +0000154 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
155 CGF.EmitBlock(DoneBB);
156 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
157 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
158 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
159 CGF.Builder.GetInsertBlock());
160 emitUntiedSwitch(CGF);
161 }
162 }
163 void emitUntiedSwitch(CodeGenFunction &CGF) const {
164 if (Untied) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000165 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000166 CGF.GetAddrOfLocalVar(PartIDVar),
167 PartIDVar->getType()->castAs<PointerType>());
168 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
169 PartIdLVal);
170 UntiedCodeGen(CGF);
171 CodeGenFunction::JumpDest CurPoint =
172 CGF.getJumpDestInCurrentScope(".untied.next.");
173 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
174 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
175 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
176 CGF.Builder.GetInsertBlock());
177 CGF.EmitBranchThroughCleanup(CurPoint);
178 CGF.EmitBlock(CurPoint.getBlock());
179 }
180 }
181 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
182 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000183 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000184 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000185 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000186 OpenMPDirectiveKind Kind, bool HasCancel,
187 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000188 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000189 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
191 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000193 /// Get a variable or parameter for storing global thread id
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000195 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000197 /// Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000198 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000199
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000200 /// Get the name of the capture helper.
Alexey Bataev62b63b12015-03-10 07:28:44 +0000201 StringRef getHelperName() const override { return ".omp_outlined."; }
202
Alexey Bataev48591dd2016-04-20 04:01:36 +0000203 void emitUntiedSwitch(CodeGenFunction &CGF) override {
204 Action.emitUntiedSwitch(CGF);
205 }
206
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000207 static bool classof(const CGCapturedStmtInfo *Info) {
208 return CGOpenMPRegionInfo::classof(Info) &&
209 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
210 TaskOutlinedRegion;
211 }
212
Alexey Bataev62b63b12015-03-10 07:28:44 +0000213private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000214 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev62b63b12015-03-10 07:28:44 +0000215 /// constructs.
216 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000217 /// Action for emitting code for untied tasks.
218 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000219};
220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221/// API for inlined captured statement code generation in OpenMP
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000222/// constructs.
223class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
224public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000225 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000226 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000227 OpenMPDirectiveKind Kind, bool HasCancel)
228 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
229 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000231
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000232 // Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000233 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000234 if (OuterRegionInfo)
235 return OuterRegionInfo->getContextValue();
236 llvm_unreachable("No context value for inlined OpenMP region");
237 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000238
Hans Wennborg7eb54642015-09-10 17:07:54 +0000239 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000240 if (OuterRegionInfo) {
241 OuterRegionInfo->setContextValue(V);
242 return;
243 }
244 llvm_unreachable("No context value for inlined OpenMP region");
245 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000247 /// Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000248 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000249 if (OuterRegionInfo)
250 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000251 // If there is no outer outlined region,no need to lookup in a list of
252 // captured variables, we can use the original one.
253 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000254 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000255
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000256 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000257 if (OuterRegionInfo)
258 return OuterRegionInfo->getThisFieldDecl();
259 return nullptr;
260 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000262 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000264 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000265 if (OuterRegionInfo)
266 return OuterRegionInfo->getThreadIDVariable();
267 return nullptr;
268 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000270 /// Get an LValue for the current ThreadID variable.
Alexey Bataev311a9282017-10-12 13:51:32 +0000271 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
272 if (OuterRegionInfo)
273 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
274 llvm_unreachable("No LValue for inlined OpenMP construct");
275 }
276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000277 /// Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000278 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000279 if (auto *OuterRegionInfo = getOldCSI())
280 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000281 llvm_unreachable("No helper name for inlined OpenMP construct");
282 }
283
Alexey Bataev48591dd2016-04-20 04:01:36 +0000284 void emitUntiedSwitch(CodeGenFunction &CGF) override {
285 if (OuterRegionInfo)
286 OuterRegionInfo->emitUntiedSwitch(CGF);
287 }
288
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000289 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
290
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000291 static bool classof(const CGCapturedStmtInfo *Info) {
292 return CGOpenMPRegionInfo::classof(Info) &&
293 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
294 }
295
Alexey Bataev48591dd2016-04-20 04:01:36 +0000296 ~CGOpenMPInlinedRegionInfo() override = default;
297
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000298private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299 /// CodeGen info about outer OpenMP region.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000300 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
301 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000302};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000304/// API for captured statement code generation in OpenMP target
Samuel Antaobed3c462015-10-02 16:14:20 +0000305/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000306/// captured fields. The name of the target region has to be unique in a given
307/// application so it is provided by the client, because only the client has
308/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000309class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000310public:
311 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000313 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000314 /*HasCancel=*/false),
315 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000317 /// This is unused for target regions because each starts executing
Samuel Antaobed3c462015-10-02 16:14:20 +0000318 /// with a single thread.
319 const VarDecl *getThreadIDVariable() const override { return nullptr; }
320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000321 /// Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000322 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000323
324 static bool classof(const CGCapturedStmtInfo *Info) {
325 return CGOpenMPRegionInfo::classof(Info) &&
326 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
327 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000328
329private:
330 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000331};
332
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000333static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000334 llvm_unreachable("No codegen for expressions");
335}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000336/// API for generation of expressions captured in a innermost OpenMP
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000338class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000339public:
340 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
341 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
342 OMPD_unknown,
343 /*HasCancel=*/false),
344 PrivScope(CGF) {
345 // Make sure the globals captured in the provided statement are local by
346 // using the privatization logic. We assume the same variable is not
347 // captured more than once.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000348 for (const auto &C : CS.captures()) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000349 if (!C.capturesVariable() && !C.capturesVariableByCopy())
350 continue;
351
352 const VarDecl *VD = C.getCapturedVar();
353 if (VD->isLocalVarDeclOrParm())
354 continue;
355
356 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
357 /*RefersToEnclosingVariableOrCapture=*/false,
358 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000359 C.getLocation());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000360 PrivScope.addPrivate(
361 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
Samuel Antaob68e2db2016-03-03 16:20:23 +0000362 }
363 (void)PrivScope.Privatize();
364 }
365
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000366 /// Lookup the captured field decl for a variable.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000367 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000368 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
Samuel Antaob68e2db2016-03-03 16:20:23 +0000369 return FD;
370 return nullptr;
371 }
372
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000373 /// Emit the captured statement body.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000374 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
375 llvm_unreachable("No body for expressions");
376 }
377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000378 /// Get a variable or parameter for storing global thread id
Samuel Antaob68e2db2016-03-03 16:20:23 +0000379 /// inside OpenMP construct.
380 const VarDecl *getThreadIDVariable() const override {
381 llvm_unreachable("No thread id for expressions");
382 }
383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000384 /// Get the name of the capture helper.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000385 StringRef getHelperName() const override {
386 llvm_unreachable("No helper name for expressions");
387 }
388
389 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
390
391private:
392 /// Private scope to capture global variables.
393 CodeGenFunction::OMPPrivateScope PrivScope;
394};
395
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000396/// RAII for emitting code of OpenMP constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000397class InlinedOpenMPRegionRAII {
398 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000399 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
400 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000401 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000402
403public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000404 /// Constructs region for combined constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000405 /// \param CodeGen Code generation sequence for combined directives. Includes
406 /// a list of functions used for code generation of implicitly inlined
407 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000408 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000409 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000410 : CGF(CGF) {
411 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000412 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
413 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000414 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
415 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
416 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000417 BlockInfo = CGF.BlockInfo;
418 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000419 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000420
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000421 ~InlinedOpenMPRegionRAII() {
422 // Restore original CapturedStmtInfo only if we're done with code emission.
423 auto *OldCSI =
424 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
425 delete CGF.CapturedStmtInfo;
426 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000427 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
428 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000429 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000430 }
431};
432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433/// Values for bit flags used in the ident_t to describe the fields.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000434/// All enumeric elements are named and described in accordance with the code
435/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000436enum OpenMPLocationFlags : unsigned {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Use trampoline for internal microtask.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000438 OMP_IDENT_IMD = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000439 /// Use c-style ident structure.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000440 OMP_IDENT_KMPC = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// Atomic reduction option for kmpc_reduce.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000442 OMP_ATOMIC_REDUCE = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000443 /// Explicit 'barrier' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000444 OMP_IDENT_BARRIER_EXPL = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// Implicit barrier in code.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000446 OMP_IDENT_BARRIER_IMPL = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Implicit barrier in 'for' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449 /// Implicit barrier in 'sections' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000450 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000451 /// Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000452 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
453 /// Call of __kmp_for_static_init for static loop.
454 OMP_IDENT_WORK_LOOP = 0x200,
455 /// Call of __kmp_for_static_init for sections.
456 OMP_IDENT_WORK_SECTIONS = 0x400,
457 /// Call of __kmp_for_static_init for distribute.
458 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
459 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000460};
461
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000462/// Describes ident structure that describes a source location.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000463/// All descriptions are taken from
464/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
465/// Original structure:
466/// typedef struct ident {
467/// kmp_int32 reserved_1; /**< might be used in Fortran;
468/// see above */
469/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
470/// KMP_IDENT_KMPC identifies this union
471/// member */
472/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
473/// see above */
474///#if USE_ITT_BUILD
475/// /* but currently used for storing
476/// region-specific ITT */
477/// /* contextual information. */
478///#endif /* USE_ITT_BUILD */
479/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
480/// C++ */
481/// char const *psource; /**< String describing the source location.
482/// The string is composed of semi-colon separated
483// fields which describe the source file,
484/// the function and a pair of line numbers that
485/// delimit the construct.
486/// */
487/// } ident_t;
488enum IdentFieldIndex {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000489 /// might be used in Fortran
Alexey Bataev50b3c952016-02-19 10:38:26 +0000490 IdentField_Reserved_1,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000491 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000492 IdentField_Flags,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Not really used in Fortran any more
Alexey Bataev50b3c952016-02-19 10:38:26 +0000494 IdentField_Reserved_2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// Source[4] in Fortran, do not use for C++
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 IdentField_Reserved_3,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000497 /// String describing the source location. The string is composed of
Alexey Bataev50b3c952016-02-19 10:38:26 +0000498 /// semi-colon separated fields which describe the source file, the function
499 /// and a pair of line numbers that delimit the construct.
500 IdentField_PSource
501};
502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000503/// Schedule types for 'omp for' loops (these enumerators are taken from
Alexey Bataev50b3c952016-02-19 10:38:26 +0000504/// the enum sched_type in kmp.h).
505enum OpenMPSchedType {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000506 /// Lower bound for default (unordered) versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000507 OMP_sch_lower = 32,
508 OMP_sch_static_chunked = 33,
509 OMP_sch_static = 34,
510 OMP_sch_dynamic_chunked = 35,
511 OMP_sch_guided_chunked = 36,
512 OMP_sch_runtime = 37,
513 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000514 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000515 OMP_sch_static_balanced_chunked = 45,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000516 /// Lower bound for 'ordered' versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000517 OMP_ord_lower = 64,
518 OMP_ord_static_chunked = 65,
519 OMP_ord_static = 66,
520 OMP_ord_dynamic_chunked = 67,
521 OMP_ord_guided_chunked = 68,
522 OMP_ord_runtime = 69,
523 OMP_ord_auto = 70,
524 OMP_sch_default = OMP_sch_static,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525 /// dist_schedule types
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000526 OMP_dist_sch_static_chunked = 91,
527 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000528 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
529 /// Set if the monotonic schedule modifier was present.
530 OMP_sch_modifier_monotonic = (1 << 29),
531 /// Set if the nonmonotonic schedule modifier was present.
532 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000533};
534
535enum OpenMPRTLFunction {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000536 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000537 /// kmpc_micro microtask, ...);
538 OMPRTL__kmpc_fork_call,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000539 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000540 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
541 OMPRTL__kmpc_threadprivate_cached,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Call to void __kmpc_threadprivate_register( ident_t *,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000543 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
544 OMPRTL__kmpc_threadprivate_register,
545 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
546 OMPRTL__kmpc_global_thread_num,
547 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
548 // kmp_critical_name *crit);
549 OMPRTL__kmpc_critical,
550 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
551 // global_tid, kmp_critical_name *crit, uintptr_t hint);
552 OMPRTL__kmpc_critical_with_hint,
553 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
554 // kmp_critical_name *crit);
555 OMPRTL__kmpc_end_critical,
556 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
557 // global_tid);
558 OMPRTL__kmpc_cancel_barrier,
559 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
560 OMPRTL__kmpc_barrier,
561 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
562 OMPRTL__kmpc_for_static_fini,
563 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
564 // global_tid);
565 OMPRTL__kmpc_serialized_parallel,
566 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
567 // global_tid);
568 OMPRTL__kmpc_end_serialized_parallel,
569 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
570 // kmp_int32 num_threads);
571 OMPRTL__kmpc_push_num_threads,
572 // Call to void __kmpc_flush(ident_t *loc);
573 OMPRTL__kmpc_flush,
574 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
575 OMPRTL__kmpc_master,
576 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
577 OMPRTL__kmpc_end_master,
578 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
579 // int end_part);
580 OMPRTL__kmpc_omp_taskyield,
581 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
582 OMPRTL__kmpc_single,
583 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
584 OMPRTL__kmpc_end_single,
585 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
586 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
587 // kmp_routine_entry_t *task_entry);
588 OMPRTL__kmpc_omp_task_alloc,
589 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
590 // new_task);
591 OMPRTL__kmpc_omp_task,
592 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
593 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
594 // kmp_int32 didit);
595 OMPRTL__kmpc_copyprivate,
596 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
597 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
598 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
599 OMPRTL__kmpc_reduce,
600 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
601 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
602 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
603 // *lck);
604 OMPRTL__kmpc_reduce_nowait,
605 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
606 // kmp_critical_name *lck);
607 OMPRTL__kmpc_end_reduce,
608 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
609 // kmp_critical_name *lck);
610 OMPRTL__kmpc_end_reduce_nowait,
611 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
612 // kmp_task_t * new_task);
613 OMPRTL__kmpc_omp_task_begin_if0,
614 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
615 // kmp_task_t * new_task);
616 OMPRTL__kmpc_omp_task_complete_if0,
617 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
618 OMPRTL__kmpc_ordered,
619 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
620 OMPRTL__kmpc_end_ordered,
621 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
622 // global_tid);
623 OMPRTL__kmpc_omp_taskwait,
624 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
625 OMPRTL__kmpc_taskgroup,
626 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
627 OMPRTL__kmpc_end_taskgroup,
628 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
629 // int proc_bind);
630 OMPRTL__kmpc_push_proc_bind,
631 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
632 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
633 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
634 OMPRTL__kmpc_omp_task_with_deps,
635 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
636 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
637 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
638 OMPRTL__kmpc_omp_wait_deps,
639 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
640 // global_tid, kmp_int32 cncl_kind);
641 OMPRTL__kmpc_cancellationpoint,
642 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
643 // kmp_int32 cncl_kind);
644 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000645 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
646 // kmp_int32 num_teams, kmp_int32 thread_limit);
647 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000648 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
649 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000650 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000651 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
652 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
653 // sched, kmp_uint64 grainsize, void *task_dup);
654 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000655 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
656 // num_dims, struct kmp_dim *dims);
657 OMPRTL__kmpc_doacross_init,
658 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
659 OMPRTL__kmpc_doacross_fini,
660 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
661 // *vec);
662 OMPRTL__kmpc_doacross_post,
663 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
664 // *vec);
665 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000666 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
667 // *data);
668 OMPRTL__kmpc_task_reduction_init,
669 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
670 // *d);
671 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000672
673 //
674 // Offloading related calls
675 //
George Rokos63bc9d62017-11-21 18:25:12 +0000676 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
677 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000678 // *arg_types);
679 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000680 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
681 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
682 // *arg_types);
683 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000684 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
685 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
686 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000687 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000688 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
689 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
690 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
691 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000692 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
693 OMPRTL__tgt_register_lib,
694 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
695 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000696 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
697 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000698 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000699 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
700 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
701 // *arg_types);
702 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000703 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
704 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000705 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000706 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
707 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
708 // *arg_types);
709 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000710 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
711 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000712 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000713 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
714 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
715 // *arg_types);
716 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000717};
718
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000719/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
720/// region.
721class CleanupTy final : public EHScopeStack::Cleanup {
722 PrePostActionTy *Action;
723
724public:
725 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
726 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
727 if (!CGF.HaveInsertPoint())
728 return;
729 Action->Exit(CGF);
730 }
731};
732
Hans Wennborg7eb54642015-09-10 17:07:54 +0000733} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000734
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000735void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
736 CodeGenFunction::RunCleanupsScope Scope(CGF);
737 if (PrePostAction) {
738 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
739 Callback(CodeGen, CGF, *PrePostAction);
740 } else {
741 PrePostActionTy Action;
742 Callback(CodeGen, CGF, Action);
743 }
744}
745
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000746/// Check if the combiner is a call to UDR combiner and if it is so return the
747/// UDR decl used for reduction.
748static const OMPDeclareReductionDecl *
749getReductionInit(const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000750 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
751 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
752 if (const auto *DRE =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000753 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000754 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000755 return DRD;
756 return nullptr;
757}
758
759static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
760 const OMPDeclareReductionDecl *DRD,
761 const Expr *InitOp,
762 Address Private, Address Original,
763 QualType Ty) {
764 if (DRD->getInitializer()) {
765 std::pair<llvm::Function *, llvm::Function *> Reduction =
766 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000767 const auto *CE = cast<CallExpr>(InitOp);
768 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000769 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
770 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000771 const auto *LHSDRE =
772 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
773 const auto *RHSDRE =
774 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000775 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
776 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000777 [=]() { return Private; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000778 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000779 [=]() { return Original; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000780 (void)PrivateScope.Privatize();
781 RValue Func = RValue::get(Reduction.second);
782 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
783 CGF.EmitIgnoredExpr(InitOp);
784 } else {
785 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
Alexey Bataev18fa2322018-05-02 14:20:50 +0000786 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000787 auto *GV = new llvm::GlobalVariable(
788 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
Alexey Bataev18fa2322018-05-02 14:20:50 +0000789 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000790 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
791 RValue InitRVal;
792 switch (CGF.getEvaluationKind(Ty)) {
793 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000794 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000795 break;
796 case TEK_Complex:
797 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000798 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000799 break;
800 case TEK_Aggregate:
801 InitRVal = RValue::getAggregate(LV.getAddress());
802 break;
803 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000804 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000805 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
806 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
807 /*IsInitializer=*/false);
808 }
809}
810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811/// Emit initialization of arrays of complex types.
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000812/// \param DestAddr Address of the array.
813/// \param Type Type of array.
814/// \param Init Initial expression of array.
815/// \param SrcAddr Address of the original array.
816static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000817 QualType Type, bool EmitDeclareReductionInit,
818 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000819 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000820 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000821 // Perform element-by-element initialization.
822 QualType ElementTy;
823
824 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000825 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
826 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000827 DestAddr =
828 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
829 if (DRD)
830 SrcAddr =
831 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
832
833 llvm::Value *SrcBegin = nullptr;
834 if (DRD)
835 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000836 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000837 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000838 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000839 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000840 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
841 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
842 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000843 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
844 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
845
846 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000847 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000848 CGF.EmitBlock(BodyBB);
849
850 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
851
852 llvm::PHINode *SrcElementPHI = nullptr;
853 Address SrcElementCurrent = Address::invalid();
854 if (DRD) {
855 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
856 "omp.arraycpy.srcElementPast");
857 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
858 SrcElementCurrent =
859 Address(SrcElementPHI,
860 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
861 }
862 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
863 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
864 DestElementPHI->addIncoming(DestBegin, EntryBB);
865 Address DestElementCurrent =
866 Address(DestElementPHI,
867 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
868
869 // Emit copy.
870 {
871 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000872 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000873 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
874 SrcElementCurrent, ElementTy);
875 } else
876 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
877 /*IsInitializer=*/false);
878 }
879
880 if (DRD) {
881 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000882 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000883 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
884 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
885 }
886
887 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000888 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000889 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
890 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000891 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000892 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
893 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
894 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
895
896 // Done.
897 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
898}
899
Alexey Bataev92327c52018-03-26 16:40:55 +0000900static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
901isDeclareTargetDeclaration(const ValueDecl *VD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000902 for (const Decl *D : VD->redecls()) {
Alexey Bataev92327c52018-03-26 16:40:55 +0000903 if (!D->hasAttrs())
904 continue;
905 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
906 return Attr->getMapType();
907 }
Alexey Bataevfb388282018-05-01 14:09:46 +0000908 if (const auto *V = dyn_cast<VarDecl>(VD)) {
909 if (const VarDecl *TD = V->getTemplateInstantiationPattern())
910 return isDeclareTargetDeclaration(TD);
911 } else if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
912 if (const auto *TD = FD->getTemplateInstantiationPattern())
913 return isDeclareTargetDeclaration(TD);
914 }
915
Alexey Bataev92327c52018-03-26 16:40:55 +0000916 return llvm::None;
917}
918
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000919LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000920 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921}
922
923LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
924 const Expr *E) {
925 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
926 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
927 return LValue();
928}
929
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000930void ReductionCodeGen::emitAggregateInitialization(
931 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
932 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000933 // Emit VarDecl with copy init for arrays.
934 // Get the address of the original variable captured in current
935 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000936 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000937 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000938 bool EmitDeclareReductionInit =
939 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000941 EmitDeclareReductionInit,
942 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
943 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000944 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000945}
946
947ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
948 ArrayRef<const Expr *> Privates,
949 ArrayRef<const Expr *> ReductionOps) {
950 ClausesData.reserve(Shareds.size());
951 SharedAddresses.reserve(Shareds.size());
952 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000953 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 auto IPriv = Privates.begin();
955 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000956 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000957 ClausesData.emplace_back(Ref, *IPriv, *IRed);
958 std::advance(IPriv, 1);
959 std::advance(IRed, 1);
960 }
961}
962
963void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
964 assert(SharedAddresses.size() == N &&
965 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000966 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
967 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
968 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000969}
970
971void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000972 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000973 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
974 QualType PrivateType = PrivateVD->getType();
975 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000976 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 Sizes.emplace_back(
978 CGF.getTypeSize(
979 SharedAddresses[N].first.getType().getNonReferenceType()),
980 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000981 return;
982 }
983 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000984 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000985 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000986 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
987 ->getElementType();
988 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000989 if (AsArraySection) {
990 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
991 SharedAddresses[N].first.getPointer());
992 Size = CGF.Builder.CreateNUWAdd(
993 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000994 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000995 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000996 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000997 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000998 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000999 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001000 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001001 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1002 CGF,
1003 cast<OpaqueValueExpr>(
1004 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1005 RValue::get(Size));
1006 CGF.EmitVariablyModifiedType(PrivateType);
1007}
1008
1009void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
1010 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001011 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001012 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1013 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001014 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001015 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001016 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001017 "items.");
1018 return;
1019 }
1020 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1021 CGF,
1022 cast<OpaqueValueExpr>(
1023 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1024 RValue::get(Size));
1025 CGF.EmitVariablyModifiedType(PrivateType);
1026}
1027
1028void ReductionCodeGen::emitInitialization(
1029 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1030 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1031 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001032 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001033 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001034 const OMPDeclareReductionDecl *DRD =
1035 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001036 QualType PrivateType = PrivateVD->getType();
1037 PrivateAddr = CGF.Builder.CreateElementBitCast(
1038 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1039 QualType SharedType = SharedAddresses[N].first.getType();
1040 SharedLVal = CGF.MakeAddrLValue(
1041 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1042 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001043 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001044 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001045 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001046 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001047 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1048 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1049 PrivateAddr, SharedLVal.getAddress(),
1050 SharedLVal.getType());
1051 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1052 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1053 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1054 PrivateVD->getType().getQualifiers(),
1055 /*IsInitializer=*/false);
1056 }
1057}
1058
1059bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001060 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001061 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1062 QualType PrivateType = PrivateVD->getType();
1063 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1064 return DTorKind != QualType::DK_none;
1065}
1066
1067void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1068 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001069 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001070 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1071 QualType PrivateType = PrivateVD->getType();
1072 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1073 if (needCleanups(N)) {
1074 PrivateAddr = CGF.Builder.CreateElementBitCast(
1075 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1076 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1077 }
1078}
1079
1080static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1081 LValue BaseLV) {
1082 BaseTy = BaseTy.getNonReferenceType();
1083 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1084 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001085 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001086 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001087 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001088 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1089 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001090 }
1091 BaseTy = BaseTy->getPointeeType();
1092 }
1093 return CGF.MakeAddrLValue(
1094 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1095 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001096 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001097 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001098}
1099
1100static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1101 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1102 llvm::Value *Addr) {
1103 Address Tmp = Address::invalid();
1104 Address TopTmp = Address::invalid();
1105 Address MostTopTmp = Address::invalid();
1106 BaseTy = BaseTy.getNonReferenceType();
1107 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1108 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1109 Tmp = CGF.CreateMemTemp(BaseTy);
1110 if (TopTmp.isValid())
1111 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1112 else
1113 MostTopTmp = Tmp;
1114 TopTmp = Tmp;
1115 BaseTy = BaseTy->getPointeeType();
1116 }
1117 llvm::Type *Ty = BaseLVType;
1118 if (Tmp.isValid())
1119 Ty = Tmp.getElementType();
1120 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1121 if (Tmp.isValid()) {
1122 CGF.Builder.CreateStore(Addr, Tmp);
1123 return MostTopTmp;
1124 }
1125 return Address(Addr, BaseLVAlignment);
1126}
1127
Alexey Bataev1c44e152018-03-06 18:59:43 +00001128static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001129 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001130 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1131 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1132 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001133 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001134 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 Base = TempASE->getBase()->IgnoreParenImpCasts();
1136 DE = cast<DeclRefExpr>(Base);
1137 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001138 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1139 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1140 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001141 Base = TempASE->getBase()->IgnoreParenImpCasts();
1142 DE = cast<DeclRefExpr>(Base);
1143 OrigVD = cast<VarDecl>(DE->getDecl());
1144 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001145 return OrigVD;
1146}
1147
1148Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1149 Address PrivateAddr) {
1150 const DeclRefExpr *DE;
1151 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001152 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001153 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001154 LValue BaseLValue =
1155 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1156 OriginalBaseLValue);
1157 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1158 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001159 llvm::Value *PrivatePointer =
1160 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1161 PrivateAddr.getPointer(),
1162 SharedAddresses[N].first.getAddress().getType());
1163 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001164 return castToBase(CGF, OrigVD->getType(),
1165 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001166 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001167 OriginalBaseLValue.getAlignment(), Ptr);
1168 }
1169 BaseDecls.emplace_back(
1170 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1171 return PrivateAddr;
1172}
1173
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001174bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001175 const OMPDeclareReductionDecl *DRD =
1176 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001177 return DRD && DRD->getInitializer();
1178}
1179
Alexey Bataev18095712014-10-10 12:19:54 +00001180LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001181 return CGF.EmitLoadOfPointerLValue(
1182 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1183 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001184}
1185
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001186void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001187 if (!CGF.HaveInsertPoint())
1188 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001189 // 1.2.2 OpenMP Language Terminology
1190 // Structured block - An executable statement with a single entry at the
1191 // top and a single exit at the bottom.
1192 // The point of exit cannot be a branch out of the structured block.
1193 // longjmp() and throw() must not violate the entry/exit criteria.
1194 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001195 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001196 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001197}
1198
Alexey Bataev62b63b12015-03-10 07:28:44 +00001199LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1200 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001201 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1202 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001203 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001204}
1205
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001206static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1207 QualType FieldTy) {
1208 auto *Field = FieldDecl::Create(
1209 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1210 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1211 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1212 Field->setAccess(AS_public);
1213 DC->addDecl(Field);
1214 return Field;
1215}
1216
Alexey Bataev18fa2322018-05-02 14:20:50 +00001217CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1218 StringRef Separator)
1219 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1220 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001221 ASTContext &C = CGM.getContext();
1222 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1223 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1224 RD->startDefinition();
1225 // reserved_1
1226 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1227 // flags
1228 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1229 // reserved_2
1230 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1231 // reserved_3
1232 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1233 // psource
1234 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1235 RD->completeDefinition();
1236 IdentQTy = C.getRecordType(RD);
1237 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001238 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001239
1240 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001241}
1242
Alexey Bataev91797552015-03-18 04:13:55 +00001243void CGOpenMPRuntime::clear() {
1244 InternalVars.clear();
1245}
1246
Alexey Bataev18fa2322018-05-02 14:20:50 +00001247std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1248 SmallString<128> Buffer;
1249 llvm::raw_svector_ostream OS(Buffer);
1250 StringRef Sep = FirstSeparator;
1251 for (StringRef Part : Parts) {
1252 OS << Sep << Part;
1253 Sep = Separator;
1254 }
1255 return OS.str();
1256}
1257
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001258static llvm::Function *
1259emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1260 const Expr *CombinerInitializer, const VarDecl *In,
1261 const VarDecl *Out, bool IsCombiner) {
1262 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001263 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001264 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1265 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001266 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001267 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001268 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001269 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001270 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001271 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001272 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001273 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001274 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001275 std::string Name = CGM.getOpenMPRuntime().getName(
1276 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1277 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1278 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001279 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001280 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001281 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001282 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001283 CodeGenFunction CGF(CGM);
1284 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1285 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001286 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1287 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001288 CodeGenFunction::OMPPrivateScope Scope(CGF);
1289 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001290 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001291 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1292 .getAddress();
1293 });
1294 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001295 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001296 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1297 .getAddress();
1298 });
1299 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001300 if (!IsCombiner && Out->hasInit() &&
1301 !CGF.isTrivialInitializer(Out->getInit())) {
1302 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1303 Out->getType().getQualifiers(),
1304 /*IsInitializer=*/true);
1305 }
1306 if (CombinerInitializer)
1307 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001308 Scope.ForceCleanup();
1309 CGF.FinishFunction();
1310 return Fn;
1311}
1312
1313void CGOpenMPRuntime::emitUserDefinedReduction(
1314 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1315 if (UDRMap.count(D) > 0)
1316 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001317 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001318 if (!In || !Out) {
1319 In = &C.Idents.get("omp_in");
1320 Out = &C.Idents.get("omp_out");
1321 }
1322 llvm::Function *Combiner = emitCombinerOrInitializer(
1323 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1324 cast<VarDecl>(D->lookup(Out).front()),
1325 /*IsCombiner=*/true);
1326 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001327 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001328 if (!Priv || !Orig) {
1329 Priv = &C.Idents.get("omp_priv");
1330 Orig = &C.Idents.get("omp_orig");
1331 }
1332 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001333 CGM, D->getType(),
1334 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1335 : nullptr,
1336 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001337 cast<VarDecl>(D->lookup(Priv).front()),
1338 /*IsCombiner=*/false);
1339 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001340 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001341 if (CGF) {
1342 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1343 Decls.second.push_back(D);
1344 }
1345}
1346
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001347std::pair<llvm::Function *, llvm::Function *>
1348CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1349 auto I = UDRMap.find(D);
1350 if (I != UDRMap.end())
1351 return I->second;
1352 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1353 return UDRMap.lookup(D);
1354}
1355
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001356static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1357 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1358 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1359 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001360 assert(ThreadIDVar->getType()->isPointerType() &&
1361 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001362 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001363 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001364 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001365 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001366 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001367 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001368 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001369 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001370 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001371 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001372 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001373 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001374 else if (const auto *OPFD =
1375 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001376 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001377 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001378 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1379 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001380 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001381 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001382 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001383 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001384}
1385
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001386llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1387 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1388 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1389 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1390 return emitParallelOrTeamsOutlinedFunction(
1391 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1392}
1393
1394llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1395 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1396 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1397 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1398 return emitParallelOrTeamsOutlinedFunction(
1399 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1400}
1401
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001402llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1403 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001404 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1405 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1406 bool Tied, unsigned &NumberOfParts) {
1407 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1408 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001409 llvm::Value *ThreadID = getThreadID(CGF, D.getLocStart());
1410 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001411 llvm::Value *TaskArgs[] = {
1412 UpLoc, ThreadID,
1413 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1414 TaskTVar->getType()->castAs<PointerType>())
1415 .getPointer()};
1416 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1417 };
1418 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1419 UntiedCodeGen);
1420 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001421 assert(!ThreadIDVar->getType()->isPointerType() &&
1422 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001423 const OpenMPDirectiveKind Region =
1424 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1425 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001426 const CapturedStmt *CS = D.getCapturedStmt(Region);
1427 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001428 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001429 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1430 InnermostKind,
1431 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001432 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001433 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001434 if (!Tied)
1435 NumberOfParts = Action.getNumberOfParts();
1436 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001437}
1438
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001439static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1440 const RecordDecl *RD, const CGRecordLayout &RL,
1441 ArrayRef<llvm::Constant *> Data) {
1442 llvm::StructType *StructTy = RL.getLLVMType();
1443 unsigned PrevIdx = 0;
1444 ConstantInitBuilder CIBuilder(CGM);
1445 auto DI = Data.begin();
1446 for (const FieldDecl *FD : RD->fields()) {
1447 unsigned Idx = RL.getLLVMFieldNo(FD);
1448 // Fill the alignment.
1449 for (unsigned I = PrevIdx; I < Idx; ++I)
1450 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1451 PrevIdx = Idx + 1;
1452 Fields.add(*DI);
1453 ++DI;
1454 }
1455}
1456
1457template <class... As>
1458static llvm::GlobalVariable *
1459createConstantGlobalStruct(CodeGenModule &CGM, QualType Ty,
1460 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1461 As &&... Args) {
1462 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1463 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1464 ConstantInitBuilder CIBuilder(CGM);
1465 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1466 buildStructValue(Fields, CGM, RD, RL, Data);
1467 return Fields.finishAndCreateGlobal(
1468 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty),
1469 /*isConstant=*/true, std::forward<As>(Args)...);
1470}
1471
1472template <typename T>
Benjamin Kramer651d0bf2018-05-15 21:26:47 +00001473static void
1474createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1475 ArrayRef<llvm::Constant *> Data,
1476 T &Parent) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001477 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1478 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1479 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1480 buildStructValue(Fields, CGM, RD, RL, Data);
1481 Fields.finishAndAddTo(Parent);
1482}
1483
Alexey Bataev50b3c952016-02-19 10:38:26 +00001484Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001485 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001486 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001487 if (!Entry) {
1488 if (!DefaultOpenMPPSource) {
1489 // Initialize default location for psource field of ident_t structure of
1490 // all ident_t objects. Format is ";file;function;line;column;;".
1491 // Taken from
1492 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1493 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001494 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001495 DefaultOpenMPPSource =
1496 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1497 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001498
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001499 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1500 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1501 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1502 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1503 DefaultOpenMPPSource};
1504 llvm::GlobalValue *DefaultOpenMPLocation = createConstantGlobalStruct(
1505 CGM, IdentQTy, Data, "", llvm::GlobalValue::PrivateLinkage);
1506 DefaultOpenMPLocation->setUnnamedAddr(
1507 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001508
John McCall7f416cc2015-09-08 08:05:57 +00001509 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001510 }
John McCall7f416cc2015-09-08 08:05:57 +00001511 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001512}
1513
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001514llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1515 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001516 unsigned Flags) {
1517 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001518 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001519 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001520 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001521 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001522
1523 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1524
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001525 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001526 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001527 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1528 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001529 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001530
Alexander Musmanc6388682014-12-15 07:07:06 +00001531 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1532 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001533 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001534 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001535 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001536 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001537 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001538 LocValue = AI;
1539
1540 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1541 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001542 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001543 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001544 }
1545
1546 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001547 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1548 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1549 LValue PSource =
1550 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001551
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001552 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001553 if (OMPDebugLoc == nullptr) {
1554 SmallString<128> Buffer2;
1555 llvm::raw_svector_ostream OS2(Buffer2);
1556 // Build debug location
1557 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1558 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001559 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001560 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001561 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1562 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1563 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001564 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001565 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001566 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001567
John McCall7f416cc2015-09-08 08:05:57 +00001568 // Our callers always pass this to a runtime function, so for
1569 // convenience, go ahead and return a naked pointer.
1570 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001571}
1572
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001573llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1574 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001575 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1576
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001577 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001578 // Check whether we've already cached a load of the thread id in this
1579 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001580 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001581 if (I != OpenMPLocThreadIDMap.end()) {
1582 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001583 if (ThreadID != nullptr)
1584 return ThreadID;
1585 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001586 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001587 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1588 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001589 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001590 if (auto *OMPRegionInfo =
1591 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1592 if (OMPRegionInfo->getThreadIDVariable()) {
1593 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001594 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001595 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001596 // If value loaded in entry block, cache it and use it everywhere in
1597 // function.
1598 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1599 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1600 Elem.second.ThreadID = ThreadID;
1601 }
1602 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001603 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001604 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001605 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001606
1607 // This is not an outlined function region - need to call __kmpc_int32
1608 // kmpc_global_thread_num(ident_t *loc).
1609 // Generate thread id value and cache this value for use across the
1610 // function.
1611 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1612 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001613 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001614 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1615 emitUpdateLocation(CGF, Loc));
1616 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001617 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001618 Elem.second.ThreadID = Call;
1619 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001620}
1621
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001622void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001623 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001624 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1625 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001626 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001627 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001628 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001629 FunctionUDRMap.erase(CGF.CurFn);
1630 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001631}
1632
1633llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001634 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001635}
1636
1637llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001638 if (!Kmpc_MicroTy) {
1639 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1640 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1641 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1642 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1643 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001644 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1645}
1646
1647llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001648CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001649 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001650 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001651 case OMPRTL__kmpc_fork_call: {
1652 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1653 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001654 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1655 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001656 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001657 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001658 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1659 break;
1660 }
1661 case OMPRTL__kmpc_global_thread_num: {
1662 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001663 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001664 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001665 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001666 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1667 break;
1668 }
Alexey Bataev97720002014-11-11 04:05:39 +00001669 case OMPRTL__kmpc_threadprivate_cached: {
1670 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1671 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1673 CGM.VoidPtrTy, CGM.SizeTy,
1674 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001675 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001676 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1677 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1678 break;
1679 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001680 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001681 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1682 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001683 llvm::Type *TypeParams[] = {
1684 getIdentTyPointerTy(), CGM.Int32Ty,
1685 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001686 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001687 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1688 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1689 break;
1690 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001691 case OMPRTL__kmpc_critical_with_hint: {
1692 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1693 // kmp_critical_name *crit, uintptr_t hint);
1694 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1695 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1696 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001697 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001698 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1699 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1700 break;
1701 }
Alexey Bataev97720002014-11-11 04:05:39 +00001702 case OMPRTL__kmpc_threadprivate_register: {
1703 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1704 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1705 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001706 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001707 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1708 /*isVarArg*/ false)->getPointerTo();
1709 // typedef void *(*kmpc_cctor)(void *, void *);
1710 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001711 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001712 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001713 /*isVarArg*/ false)
1714 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001715 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001716 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001717 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1718 ->getPointerTo();
1719 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1720 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001721 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001722 /*isVarArg*/ false);
1723 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1724 break;
1725 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001726 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001727 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1728 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001729 llvm::Type *TypeParams[] = {
1730 getIdentTyPointerTy(), CGM.Int32Ty,
1731 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001732 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001733 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1734 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1735 break;
1736 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001737 case OMPRTL__kmpc_cancel_barrier: {
1738 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1739 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001740 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001741 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001742 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1743 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001744 break;
1745 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001746 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001747 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001748 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001749 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001750 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1751 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1752 break;
1753 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001754 case OMPRTL__kmpc_for_static_fini: {
1755 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1756 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001757 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001758 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1759 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1760 break;
1761 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001762 case OMPRTL__kmpc_push_num_threads: {
1763 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1764 // kmp_int32 num_threads)
1765 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1766 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001767 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001768 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1769 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1770 break;
1771 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001772 case OMPRTL__kmpc_serialized_parallel: {
1773 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1774 // global_tid);
1775 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001776 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001777 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1778 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1779 break;
1780 }
1781 case OMPRTL__kmpc_end_serialized_parallel: {
1782 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1783 // global_tid);
1784 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001785 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001786 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1787 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1788 break;
1789 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001790 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001791 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001792 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001793 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001794 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001795 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1796 break;
1797 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001798 case OMPRTL__kmpc_master: {
1799 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1800 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001801 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001802 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1803 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1804 break;
1805 }
1806 case OMPRTL__kmpc_end_master: {
1807 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1808 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001809 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001810 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1811 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1812 break;
1813 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001814 case OMPRTL__kmpc_omp_taskyield: {
1815 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1816 // int end_part);
1817 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001818 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001819 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1820 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1821 break;
1822 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001823 case OMPRTL__kmpc_single: {
1824 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1825 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001826 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001827 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1828 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1829 break;
1830 }
1831 case OMPRTL__kmpc_end_single: {
1832 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1833 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001834 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001835 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1836 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1837 break;
1838 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001839 case OMPRTL__kmpc_omp_task_alloc: {
1840 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1841 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1842 // kmp_routine_entry_t *task_entry);
1843 assert(KmpRoutineEntryPtrTy != nullptr &&
1844 "Type kmp_routine_entry_t must be created.");
1845 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1846 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1847 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001848 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001849 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1850 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1851 break;
1852 }
1853 case OMPRTL__kmpc_omp_task: {
1854 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1855 // *new_task);
1856 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1857 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001858 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001859 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1860 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1861 break;
1862 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001863 case OMPRTL__kmpc_copyprivate: {
1864 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001865 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001866 // kmp_int32 didit);
1867 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1868 auto *CpyFnTy =
1869 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001870 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001871 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1872 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001873 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001874 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1875 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1876 break;
1877 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001878 case OMPRTL__kmpc_reduce: {
1879 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1880 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1881 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1882 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1883 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1884 /*isVarArg=*/false);
1885 llvm::Type *TypeParams[] = {
1886 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1887 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1888 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001889 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001890 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1891 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1892 break;
1893 }
1894 case OMPRTL__kmpc_reduce_nowait: {
1895 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1896 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1897 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1898 // *lck);
1899 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1900 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1901 /*isVarArg=*/false);
1902 llvm::Type *TypeParams[] = {
1903 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1904 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1905 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001906 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001907 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1908 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1909 break;
1910 }
1911 case OMPRTL__kmpc_end_reduce: {
1912 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1913 // kmp_critical_name *lck);
1914 llvm::Type *TypeParams[] = {
1915 getIdentTyPointerTy(), CGM.Int32Ty,
1916 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001917 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001918 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1919 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1920 break;
1921 }
1922 case OMPRTL__kmpc_end_reduce_nowait: {
1923 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1924 // kmp_critical_name *lck);
1925 llvm::Type *TypeParams[] = {
1926 getIdentTyPointerTy(), CGM.Int32Ty,
1927 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001928 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001929 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1930 RTLFn =
1931 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1932 break;
1933 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001934 case OMPRTL__kmpc_omp_task_begin_if0: {
1935 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1936 // *new_task);
1937 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1938 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001939 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001940 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1941 RTLFn =
1942 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1943 break;
1944 }
1945 case OMPRTL__kmpc_omp_task_complete_if0: {
1946 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1947 // *new_task);
1948 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1949 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001950 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001951 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1952 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1953 /*Name=*/"__kmpc_omp_task_complete_if0");
1954 break;
1955 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001956 case OMPRTL__kmpc_ordered: {
1957 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1958 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001959 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001960 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1961 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1962 break;
1963 }
1964 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001965 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001967 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001968 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1969 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1970 break;
1971 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001972 case OMPRTL__kmpc_omp_taskwait: {
1973 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1974 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001975 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001976 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1977 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1978 break;
1979 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001980 case OMPRTL__kmpc_taskgroup: {
1981 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1982 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001983 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001984 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1985 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1986 break;
1987 }
1988 case OMPRTL__kmpc_end_taskgroup: {
1989 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1990 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001991 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001992 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1993 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1994 break;
1995 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001996 case OMPRTL__kmpc_push_proc_bind: {
1997 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1998 // int proc_bind)
1999 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002000 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002001 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2002 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2003 break;
2004 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002005 case OMPRTL__kmpc_omp_task_with_deps: {
2006 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2007 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2008 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2009 llvm::Type *TypeParams[] = {
2010 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2011 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002012 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002013 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2014 RTLFn =
2015 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2016 break;
2017 }
2018 case OMPRTL__kmpc_omp_wait_deps: {
2019 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2020 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2021 // kmp_depend_info_t *noalias_dep_list);
2022 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2023 CGM.Int32Ty, CGM.VoidPtrTy,
2024 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002025 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002026 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2027 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2028 break;
2029 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002030 case OMPRTL__kmpc_cancellationpoint: {
2031 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2032 // global_tid, kmp_int32 cncl_kind)
2033 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002034 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002035 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2036 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2037 break;
2038 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002039 case OMPRTL__kmpc_cancel: {
2040 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2041 // kmp_int32 cncl_kind)
2042 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002043 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002044 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2045 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2046 break;
2047 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002048 case OMPRTL__kmpc_push_num_teams: {
2049 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2050 // kmp_int32 num_teams, kmp_int32 num_threads)
2051 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2052 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002053 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002054 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2055 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2056 break;
2057 }
2058 case OMPRTL__kmpc_fork_teams: {
2059 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2060 // microtask, ...);
2061 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2062 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002063 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002064 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2065 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2066 break;
2067 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002068 case OMPRTL__kmpc_taskloop: {
2069 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2070 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2071 // sched, kmp_uint64 grainsize, void *task_dup);
2072 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2073 CGM.IntTy,
2074 CGM.VoidPtrTy,
2075 CGM.IntTy,
2076 CGM.Int64Ty->getPointerTo(),
2077 CGM.Int64Ty->getPointerTo(),
2078 CGM.Int64Ty,
2079 CGM.IntTy,
2080 CGM.IntTy,
2081 CGM.Int64Ty,
2082 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002083 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002084 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2085 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2086 break;
2087 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002088 case OMPRTL__kmpc_doacross_init: {
2089 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2090 // num_dims, struct kmp_dim *dims);
2091 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2092 CGM.Int32Ty,
2093 CGM.Int32Ty,
2094 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002095 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002096 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2097 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2098 break;
2099 }
2100 case OMPRTL__kmpc_doacross_fini: {
2101 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2102 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002103 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002104 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2105 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2106 break;
2107 }
2108 case OMPRTL__kmpc_doacross_post: {
2109 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2110 // *vec);
2111 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2112 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002113 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002114 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2115 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2116 break;
2117 }
2118 case OMPRTL__kmpc_doacross_wait: {
2119 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2120 // *vec);
2121 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2122 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002123 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002124 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2125 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2126 break;
2127 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002128 case OMPRTL__kmpc_task_reduction_init: {
2129 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2130 // *data);
2131 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002132 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002133 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2134 RTLFn =
2135 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2136 break;
2137 }
2138 case OMPRTL__kmpc_task_reduction_get_th_data: {
2139 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2140 // *d);
2141 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002142 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002143 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2144 RTLFn = CGM.CreateRuntimeFunction(
2145 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2146 break;
2147 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002148 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002149 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2150 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002151 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002152 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002153 CGM.VoidPtrTy,
2154 CGM.Int32Ty,
2155 CGM.VoidPtrPtrTy,
2156 CGM.VoidPtrPtrTy,
2157 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002158 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002159 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002160 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2161 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2162 break;
2163 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002164 case OMPRTL__tgt_target_nowait: {
2165 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2166 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2167 // int64_t *arg_types);
2168 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2169 CGM.VoidPtrTy,
2170 CGM.Int32Ty,
2171 CGM.VoidPtrPtrTy,
2172 CGM.VoidPtrPtrTy,
2173 CGM.SizeTy->getPointerTo(),
2174 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002175 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002176 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2177 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2178 break;
2179 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002180 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002181 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002182 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002183 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2184 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002185 CGM.VoidPtrTy,
2186 CGM.Int32Ty,
2187 CGM.VoidPtrPtrTy,
2188 CGM.VoidPtrPtrTy,
2189 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002190 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002191 CGM.Int32Ty,
2192 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002193 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002194 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2195 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2196 break;
2197 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002198 case OMPRTL__tgt_target_teams_nowait: {
2199 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2200 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2201 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2202 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2203 CGM.VoidPtrTy,
2204 CGM.Int32Ty,
2205 CGM.VoidPtrPtrTy,
2206 CGM.VoidPtrPtrTy,
2207 CGM.SizeTy->getPointerTo(),
2208 CGM.Int64Ty->getPointerTo(),
2209 CGM.Int32Ty,
2210 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002211 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002212 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2213 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2214 break;
2215 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002216 case OMPRTL__tgt_register_lib: {
2217 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2218 QualType ParamTy =
2219 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2220 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002221 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002222 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2223 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2224 break;
2225 }
2226 case OMPRTL__tgt_unregister_lib: {
2227 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2228 QualType ParamTy =
2229 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2230 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002231 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002232 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2233 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2234 break;
2235 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002236 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002237 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2238 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2239 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002240 CGM.Int32Ty,
2241 CGM.VoidPtrPtrTy,
2242 CGM.VoidPtrPtrTy,
2243 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002244 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002245 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002246 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2247 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2248 break;
2249 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002250 case OMPRTL__tgt_target_data_begin_nowait: {
2251 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2252 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2253 // *arg_types);
2254 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2255 CGM.Int32Ty,
2256 CGM.VoidPtrPtrTy,
2257 CGM.VoidPtrPtrTy,
2258 CGM.SizeTy->getPointerTo(),
2259 CGM.Int64Ty->getPointerTo()};
2260 auto *FnTy =
2261 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2262 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2263 break;
2264 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002265 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002266 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2267 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2268 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002269 CGM.Int32Ty,
2270 CGM.VoidPtrPtrTy,
2271 CGM.VoidPtrPtrTy,
2272 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002273 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002274 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002275 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2276 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2277 break;
2278 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002279 case OMPRTL__tgt_target_data_end_nowait: {
2280 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2281 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2282 // *arg_types);
2283 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2284 CGM.Int32Ty,
2285 CGM.VoidPtrPtrTy,
2286 CGM.VoidPtrPtrTy,
2287 CGM.SizeTy->getPointerTo(),
2288 CGM.Int64Ty->getPointerTo()};
2289 auto *FnTy =
2290 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2291 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2292 break;
2293 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002294 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002295 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2296 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2297 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002298 CGM.Int32Ty,
2299 CGM.VoidPtrPtrTy,
2300 CGM.VoidPtrPtrTy,
2301 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002302 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002303 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002304 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2305 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2306 break;
2307 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002308 case OMPRTL__tgt_target_data_update_nowait: {
2309 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2310 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2311 // *arg_types);
2312 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2313 CGM.Int32Ty,
2314 CGM.VoidPtrPtrTy,
2315 CGM.VoidPtrPtrTy,
2316 CGM.SizeTy->getPointerTo(),
2317 CGM.Int64Ty->getPointerTo()};
2318 auto *FnTy =
2319 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2320 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2321 break;
2322 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002323 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002324 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002325 return RTLFn;
2326}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002327
Alexander Musman21212e42015-03-13 10:38:23 +00002328llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2329 bool IVSigned) {
2330 assert((IVSize == 32 || IVSize == 64) &&
2331 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002332 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2333 : "__kmpc_for_static_init_4u")
2334 : (IVSigned ? "__kmpc_for_static_init_8"
2335 : "__kmpc_for_static_init_8u");
2336 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2337 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002338 llvm::Type *TypeParams[] = {
2339 getIdentTyPointerTy(), // loc
2340 CGM.Int32Ty, // tid
2341 CGM.Int32Ty, // schedtype
2342 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2343 PtrTy, // p_lower
2344 PtrTy, // p_upper
2345 PtrTy, // p_stride
2346 ITy, // incr
2347 ITy // chunk
2348 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002349 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002350 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2351 return CGM.CreateRuntimeFunction(FnTy, Name);
2352}
2353
Alexander Musman92bdaab2015-03-12 13:37:50 +00002354llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2355 bool IVSigned) {
2356 assert((IVSize == 32 || IVSize == 64) &&
2357 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002358 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002359 IVSize == 32
2360 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2361 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002362 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002363 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2364 CGM.Int32Ty, // tid
2365 CGM.Int32Ty, // schedtype
2366 ITy, // lower
2367 ITy, // upper
2368 ITy, // stride
2369 ITy // chunk
2370 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002371 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002372 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2373 return CGM.CreateRuntimeFunction(FnTy, Name);
2374}
2375
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002376llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2377 bool IVSigned) {
2378 assert((IVSize == 32 || IVSize == 64) &&
2379 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002380 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002381 IVSize == 32
2382 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2383 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2384 llvm::Type *TypeParams[] = {
2385 getIdentTyPointerTy(), // loc
2386 CGM.Int32Ty, // tid
2387 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002388 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002389 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2390 return CGM.CreateRuntimeFunction(FnTy, Name);
2391}
2392
Alexander Musman92bdaab2015-03-12 13:37:50 +00002393llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2394 bool IVSigned) {
2395 assert((IVSize == 32 || IVSize == 64) &&
2396 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002397 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002398 IVSize == 32
2399 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2400 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002401 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2402 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002403 llvm::Type *TypeParams[] = {
2404 getIdentTyPointerTy(), // loc
2405 CGM.Int32Ty, // tid
2406 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2407 PtrTy, // p_lower
2408 PtrTy, // p_upper
2409 PtrTy // p_stride
2410 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002411 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002412 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2413 return CGM.CreateRuntimeFunction(FnTy, Name);
2414}
2415
Alexey Bataev03f270c2018-03-30 18:31:07 +00002416Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2417 if (CGM.getLangOpts().OpenMPSimd)
2418 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002419 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2420 isDeclareTargetDeclaration(VD);
2421 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2422 SmallString<64> PtrName;
2423 {
2424 llvm::raw_svector_ostream OS(PtrName);
2425 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2426 }
2427 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2428 if (!Ptr) {
2429 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2430 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2431 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002432 if (!CGM.getLangOpts().OpenMPIsDevice) {
2433 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2434 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2435 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2436 }
2437 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2438 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002439 }
2440 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2441 }
2442 return Address::invalid();
2443}
2444
Alexey Bataev97720002014-11-11 04:05:39 +00002445llvm::Constant *
2446CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002447 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2448 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002449 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002450 std::string Suffix = getName({"cache", ""});
2451 return getOrCreateInternalVariable(
2452 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002453}
2454
John McCall7f416cc2015-09-08 08:05:57 +00002455Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2456 const VarDecl *VD,
2457 Address VDAddr,
2458 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002459 if (CGM.getLangOpts().OpenMPUseTLS &&
2460 CGM.getContext().getTargetInfo().isTLSSupported())
2461 return VDAddr;
2462
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002463 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002464 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002465 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2466 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002467 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2468 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002469 return Address(CGF.EmitRuntimeCall(
2470 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2471 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002472}
2473
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002474void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002475 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002476 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2477 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2478 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002479 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002480 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002481 OMPLoc);
2482 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2483 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002484 llvm::Value *Args[] = {
2485 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2486 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002487 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002488 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002489}
2490
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002491llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002492 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002493 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002494 if (CGM.getLangOpts().OpenMPUseTLS &&
2495 CGM.getContext().getTargetInfo().isTLSSupported())
2496 return nullptr;
2497
Alexey Bataev97720002014-11-11 04:05:39 +00002498 VD = VD->getDefinition(CGM.getContext());
2499 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2500 ThreadPrivateWithDefinition.insert(VD);
2501 QualType ASTTy = VD->getType();
2502
2503 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002504 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002505 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2506 // Generate function that re-emits the declaration's initializer into the
2507 // threadprivate copy of the variable VD
2508 CodeGenFunction CtorCGF(CGM);
2509 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002510 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2511 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002512 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002513 Args.push_back(&Dst);
2514
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002515 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002516 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002517 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002518 std::string Name = getName({"__kmpc_global_ctor_", ""});
2519 llvm::Function *Fn =
2520 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002521 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002522 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002523 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002524 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002525 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002526 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002527 Arg = CtorCGF.Builder.CreateElementBitCast(
2528 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002529 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2530 /*IsInitializer=*/true);
2531 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002532 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002533 CGM.getContext().VoidPtrTy, Dst.getLocation());
2534 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2535 CtorCGF.FinishFunction();
2536 Ctor = Fn;
2537 }
2538 if (VD->getType().isDestructedType() != QualType::DK_none) {
2539 // Generate function that emits destructor call for the threadprivate copy
2540 // of the variable VD
2541 CodeGenFunction DtorCGF(CGM);
2542 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002543 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2544 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002545 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002546 Args.push_back(&Dst);
2547
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002548 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002549 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002550 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002551 std::string Name = getName({"__kmpc_global_dtor_", ""});
2552 llvm::Function *Fn =
2553 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002554 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002555 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002556 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002557 // Create a scope with an artificial location for the body of this function.
2558 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002559 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002560 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002561 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2562 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002563 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2564 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2565 DtorCGF.FinishFunction();
2566 Dtor = Fn;
2567 }
2568 // Do not emit init function if it is not required.
2569 if (!Ctor && !Dtor)
2570 return nullptr;
2571
2572 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002573 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2574 /*isVarArg=*/false)
2575 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002576 // Copying constructor for the threadprivate variable.
2577 // Must be NULL - reserved by runtime, but currently it requires that this
2578 // parameter is always NULL. Otherwise it fires assertion.
2579 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2580 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002581 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2582 /*isVarArg=*/false)
2583 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002584 Ctor = llvm::Constant::getNullValue(CtorTy);
2585 }
2586 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002587 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2588 /*isVarArg=*/false)
2589 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002590 Dtor = llvm::Constant::getNullValue(DtorTy);
2591 }
2592 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002593 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002594 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002595 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002596 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002597 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002598 CodeGenFunction InitCGF(CGM);
2599 FunctionArgList ArgList;
2600 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2601 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002602 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002603 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002604 InitCGF.FinishFunction();
2605 return InitFunction;
2606 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002607 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002608 }
2609 return nullptr;
2610}
2611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002612/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002613/// consists of the file and device IDs as well as line number associated with
2614/// the relevant entry source location.
2615static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2616 unsigned &DeviceID, unsigned &FileID,
2617 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002618 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002619
2620 // The loc should be always valid and have a file ID (the user cannot use
2621 // #pragma directives in macros)
2622
2623 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002624
2625 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2626 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2627
2628 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002629 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2630 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2631 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002632
2633 DeviceID = ID.getDevice();
2634 FileID = ID.getFile();
2635 LineNum = PLoc.getLine();
2636}
2637
2638bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2639 llvm::GlobalVariable *Addr,
2640 bool PerformInit) {
2641 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2642 isDeclareTargetDeclaration(VD);
2643 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2644 return false;
2645 VD = VD->getDefinition(CGM.getContext());
2646 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2647 return CGM.getLangOpts().OpenMPIsDevice;
2648
2649 QualType ASTTy = VD->getType();
2650
2651 SourceLocation Loc = VD->getCanonicalDecl()->getLocStart();
2652 // Produce the unique prefix to identify the new target regions. We use
2653 // the source location of the variable declaration which we know to not
2654 // conflict with any target region.
2655 unsigned DeviceID;
2656 unsigned FileID;
2657 unsigned Line;
2658 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2659 SmallString<128> Buffer, Out;
2660 {
2661 llvm::raw_svector_ostream OS(Buffer);
2662 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2663 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2664 }
2665
2666 const Expr *Init = VD->getAnyInitializer();
2667 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2668 llvm::Constant *Ctor;
2669 llvm::Constant *ID;
2670 if (CGM.getLangOpts().OpenMPIsDevice) {
2671 // Generate function that re-emits the declaration's initializer into
2672 // the threadprivate copy of the variable VD
2673 CodeGenFunction CtorCGF(CGM);
2674
2675 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2676 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2677 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2678 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2679 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2680 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2681 FunctionArgList(), Loc, Loc);
2682 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2683 CtorCGF.EmitAnyExprToMem(Init,
2684 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2685 Init->getType().getQualifiers(),
2686 /*IsInitializer=*/true);
2687 CtorCGF.FinishFunction();
2688 Ctor = Fn;
2689 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002690 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002691 } else {
2692 Ctor = new llvm::GlobalVariable(
2693 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2694 llvm::GlobalValue::PrivateLinkage,
2695 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2696 ID = Ctor;
2697 }
2698
2699 // Register the information for the entry associated with the constructor.
2700 Out.clear();
2701 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2702 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002703 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002704 }
2705 if (VD->getType().isDestructedType() != QualType::DK_none) {
2706 llvm::Constant *Dtor;
2707 llvm::Constant *ID;
2708 if (CGM.getLangOpts().OpenMPIsDevice) {
2709 // Generate function that emits destructor call for the threadprivate
2710 // copy of the variable VD
2711 CodeGenFunction DtorCGF(CGM);
2712
2713 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2714 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2715 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2716 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2717 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2718 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2719 FunctionArgList(), Loc, Loc);
2720 // Create a scope with an artificial location for the body of this
2721 // function.
2722 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2723 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2724 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2725 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2726 DtorCGF.FinishFunction();
2727 Dtor = Fn;
2728 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002729 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002730 } else {
2731 Dtor = new llvm::GlobalVariable(
2732 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2733 llvm::GlobalValue::PrivateLinkage,
2734 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2735 ID = Dtor;
2736 }
2737 // Register the information for the entry associated with the destructor.
2738 Out.clear();
2739 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2740 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002741 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002742 }
2743 return CGM.getLangOpts().OpenMPIsDevice;
2744}
2745
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002746Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2747 QualType VarType,
2748 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002749 std::string Suffix = getName({"artificial", ""});
2750 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002751 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002752 llvm::Value *GAddr =
2753 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002754 llvm::Value *Args[] = {
2755 emitUpdateLocation(CGF, SourceLocation()),
2756 getThreadID(CGF, SourceLocation()),
2757 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2758 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2759 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002760 getOrCreateInternalVariable(
2761 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002762 return Address(
2763 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2764 CGF.EmitRuntimeCall(
2765 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2766 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2767 CGM.getPointerAlign());
2768}
2769
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002770void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2771 const RegionCodeGenTy &ThenGen,
2772 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002773 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2774
2775 // If the condition constant folds and can be elided, try to avoid emitting
2776 // the condition and the dead arm of the if/else.
2777 bool CondConstant;
2778 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002779 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002780 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002781 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002782 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002783 return;
2784 }
2785
2786 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2787 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002788 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2789 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2790 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002791 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2792
2793 // Emit the 'then' code.
2794 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002795 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002796 CGF.EmitBranch(ContBlock);
2797 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002798 // There is no need to emit line number for unconditional branch.
2799 (void)ApplyDebugLocation::CreateEmpty(CGF);
2800 CGF.EmitBlock(ElseBlock);
2801 ElseGen(CGF);
2802 // There is no need to emit line number for unconditional branch.
2803 (void)ApplyDebugLocation::CreateEmpty(CGF);
2804 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002805 // Emit the continuation block for code after the if.
2806 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002807}
2808
Alexey Bataev1d677132015-04-22 13:57:31 +00002809void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2810 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002811 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002812 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002813 if (!CGF.HaveInsertPoint())
2814 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002815 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002816 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2817 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002818 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002819 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002820 llvm::Value *Args[] = {
2821 RTLoc,
2822 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002823 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002824 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2825 RealArgs.append(std::begin(Args), std::end(Args));
2826 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2827
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002828 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002829 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2830 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002831 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2832 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002833 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2834 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002835 // Build calls:
2836 // __kmpc_serialized_parallel(&Loc, GTid);
2837 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002838 CGF.EmitRuntimeCall(
2839 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002840
Alexey Bataev1d677132015-04-22 13:57:31 +00002841 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002842 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2843 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002844 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002845 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002846 // ThreadId for serialized parallels is 0.
2847 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002848 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2849 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002850 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002851
Alexey Bataev1d677132015-04-22 13:57:31 +00002852 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002853 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002854 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002855 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2856 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002857 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002858 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002859 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002860 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002861 RegionCodeGenTy ThenRCG(ThenGen);
2862 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002863 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002864}
2865
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002866// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002867// thread-ID variable (it is passed in a first argument of the outlined function
2868// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2869// regular serial code region, get thread ID by calling kmp_int32
2870// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2871// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002872Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2873 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002874 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002875 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002876 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002877 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002878
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002879 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2880 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002881 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002882 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002883 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002884 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002885
2886 return ThreadIDTemp;
2887}
2888
Alexey Bataev97720002014-11-11 04:05:39 +00002889llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002890CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002891 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002892 SmallString<256> Buffer;
2893 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002894 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002895 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002896 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002897 if (Elem.second) {
2898 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002899 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002900 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002901 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002902
David Blaikie13156b62014-11-19 03:06:06 +00002903 return Elem.second = new llvm::GlobalVariable(
2904 CGM.getModule(), Ty, /*IsConstant*/ false,
2905 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2906 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002907}
2908
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002909llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002910 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2911 std::string Name = getName({Prefix, "var"});
2912 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002913}
2914
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002915namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002916/// Common pre(post)-action for different OpenMP constructs.
2917class CommonActionTy final : public PrePostActionTy {
2918 llvm::Value *EnterCallee;
2919 ArrayRef<llvm::Value *> EnterArgs;
2920 llvm::Value *ExitCallee;
2921 ArrayRef<llvm::Value *> ExitArgs;
2922 bool Conditional;
2923 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002924
2925public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002926 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2927 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2928 bool Conditional = false)
2929 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2930 ExitArgs(ExitArgs), Conditional(Conditional) {}
2931 void Enter(CodeGenFunction &CGF) override {
2932 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2933 if (Conditional) {
2934 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2935 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2936 ContBlock = CGF.createBasicBlock("omp_if.end");
2937 // Generate the branch (If-stmt)
2938 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2939 CGF.EmitBlock(ThenBlock);
2940 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002941 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002942 void Done(CodeGenFunction &CGF) {
2943 // Emit the rest of blocks/branches
2944 CGF.EmitBranch(ContBlock);
2945 CGF.EmitBlock(ContBlock, true);
2946 }
2947 void Exit(CodeGenFunction &CGF) override {
2948 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002949 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002950};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002951} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002952
2953void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2954 StringRef CriticalName,
2955 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002956 SourceLocation Loc, const Expr *Hint) {
2957 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002958 // CriticalOpGen();
2959 // __kmpc_end_critical(ident_t *, gtid, Lock);
2960 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002961 if (!CGF.HaveInsertPoint())
2962 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002963 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2964 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002965 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2966 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002967 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002968 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2969 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2970 }
2971 CommonActionTy Action(
2972 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2973 : OMPRTL__kmpc_critical),
2974 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2975 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002976 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002977}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002978
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002979void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002980 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002981 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002982 if (!CGF.HaveInsertPoint())
2983 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002984 // if(__kmpc_master(ident_t *, gtid)) {
2985 // MasterOpGen();
2986 // __kmpc_end_master(ident_t *, gtid);
2987 // }
2988 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002989 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002990 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2991 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2992 /*Conditional=*/true);
2993 MasterOpGen.setAction(Action);
2994 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2995 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002996}
2997
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002998void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2999 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003000 if (!CGF.HaveInsertPoint())
3001 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003002 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3003 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003004 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003005 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003006 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003007 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3008 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003009}
3010
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003011void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3012 const RegionCodeGenTy &TaskgroupOpGen,
3013 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003014 if (!CGF.HaveInsertPoint())
3015 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003016 // __kmpc_taskgroup(ident_t *, gtid);
3017 // TaskgroupOpGen();
3018 // __kmpc_end_taskgroup(ident_t *, gtid);
3019 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003020 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3021 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3022 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3023 Args);
3024 TaskgroupOpGen.setAction(Action);
3025 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003026}
3027
John McCall7f416cc2015-09-08 08:05:57 +00003028/// Given an array of pointers to variables, project the address of a
3029/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003030static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3031 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003032 // Pull out the pointer to the variable.
3033 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003034 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003035 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3036
3037 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003038 Addr = CGF.Builder.CreateElementBitCast(
3039 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003040 return Addr;
3041}
3042
Alexey Bataeva63048e2015-03-23 06:18:07 +00003043static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003044 CodeGenModule &CGM, llvm::Type *ArgsType,
3045 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003046 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3047 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003048 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003049 // void copy_func(void *LHSArg, void *RHSArg);
3050 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003051 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3052 ImplicitParamDecl::Other);
3053 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3054 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003055 Args.push_back(&LHSArg);
3056 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003057 const auto &CGFI =
3058 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003059 std::string Name =
3060 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3061 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3062 llvm::GlobalValue::InternalLinkage, Name,
3063 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003064 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003065 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003066 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003067 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003068 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003069 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003070 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3071 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3072 ArgsType), CGF.getPointerAlign());
3073 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3074 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3075 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003076 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3077 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3078 // ...
3079 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003080 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003081 const auto *DestVar =
3082 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003083 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3084
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003085 const auto *SrcVar =
3086 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003087 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3088
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003089 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003090 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003091 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003092 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003093 CGF.FinishFunction();
3094 return Fn;
3095}
3096
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003097void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003098 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003099 SourceLocation Loc,
3100 ArrayRef<const Expr *> CopyprivateVars,
3101 ArrayRef<const Expr *> SrcExprs,
3102 ArrayRef<const Expr *> DstExprs,
3103 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003104 if (!CGF.HaveInsertPoint())
3105 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003106 assert(CopyprivateVars.size() == SrcExprs.size() &&
3107 CopyprivateVars.size() == DstExprs.size() &&
3108 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003109 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003110 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003111 // if(__kmpc_single(ident_t *, gtid)) {
3112 // SingleOpGen();
3113 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003114 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003115 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003116 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3117 // <copy_func>, did_it);
3118
John McCall7f416cc2015-09-08 08:05:57 +00003119 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003120 if (!CopyprivateVars.empty()) {
3121 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003122 QualType KmpInt32Ty =
3123 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003124 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003125 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003126 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003127 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003128 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003129 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3130 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3131 /*Conditional=*/true);
3132 SingleOpGen.setAction(Action);
3133 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3134 if (DidIt.isValid()) {
3135 // did_it = 1;
3136 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3137 }
3138 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003139 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3140 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003141 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003142 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003143 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003144 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3145 /*IndexTypeQuals=*/0);
3146 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003147 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003148 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3149 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003150 Address Elem = CGF.Builder.CreateConstArrayGEP(
3151 CopyprivateList, I, CGF.getPointerSize());
3152 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003153 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003154 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3155 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003156 }
3157 // Build function that copies private values from single region to all other
3158 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003159 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003160 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003161 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003162 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003163 Address CL =
3164 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3165 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003166 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003167 llvm::Value *Args[] = {
3168 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3169 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003170 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003171 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003172 CpyFn, // void (*) (void *, void *) <copy_func>
3173 DidItVal // i32 did_it
3174 };
3175 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3176 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003177}
3178
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003179void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3180 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003181 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003182 if (!CGF.HaveInsertPoint())
3183 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003184 // __kmpc_ordered(ident_t *, gtid);
3185 // OrderedOpGen();
3186 // __kmpc_end_ordered(ident_t *, gtid);
3187 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003188 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003189 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003190 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3191 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3192 Args);
3193 OrderedOpGen.setAction(Action);
3194 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3195 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003196 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003197 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003198}
3199
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003200void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003201 OpenMPDirectiveKind Kind, bool EmitChecks,
3202 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003203 if (!CGF.HaveInsertPoint())
3204 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003205 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003206 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003207 unsigned Flags;
3208 if (Kind == OMPD_for)
3209 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3210 else if (Kind == OMPD_sections)
3211 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3212 else if (Kind == OMPD_single)
3213 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3214 else if (Kind == OMPD_barrier)
3215 Flags = OMP_IDENT_BARRIER_EXPL;
3216 else
3217 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003218 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3219 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003220 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3221 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003222 if (auto *OMPRegionInfo =
3223 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003224 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003225 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003226 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003227 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003228 // if (__kmpc_cancel_barrier()) {
3229 // exit from construct;
3230 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003231 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3232 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3233 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003234 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3235 CGF.EmitBlock(ExitBB);
3236 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003237 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003238 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003239 CGF.EmitBranchThroughCleanup(CancelDestination);
3240 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3241 }
3242 return;
3243 }
3244 }
3245 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003246}
3247
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003248/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003249static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003250 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003251 switch (ScheduleKind) {
3252 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003253 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3254 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003255 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003256 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003257 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003258 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003259 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003260 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3261 case OMPC_SCHEDULE_auto:
3262 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003263 case OMPC_SCHEDULE_unknown:
3264 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003265 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003266 }
3267 llvm_unreachable("Unexpected runtime schedule");
3268}
3269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003270/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003271static OpenMPSchedType
3272getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3273 // only static is allowed for dist_schedule
3274 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3275}
3276
Alexander Musmanc6388682014-12-15 07:07:06 +00003277bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3278 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003279 OpenMPSchedType Schedule =
3280 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003281 return Schedule == OMP_sch_static;
3282}
3283
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003284bool CGOpenMPRuntime::isStaticNonchunked(
3285 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003286 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003287 return Schedule == OMP_dist_sch_static;
3288}
3289
3290
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003291bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003292 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003293 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003294 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3295 return Schedule != OMP_sch_static;
3296}
3297
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003298static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3299 OpenMPScheduleClauseModifier M1,
3300 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003301 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003302 switch (M1) {
3303 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003304 Modifier = OMP_sch_modifier_monotonic;
3305 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003306 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003307 Modifier = OMP_sch_modifier_nonmonotonic;
3308 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003309 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003310 if (Schedule == OMP_sch_static_chunked)
3311 Schedule = OMP_sch_static_balanced_chunked;
3312 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003313 case OMPC_SCHEDULE_MODIFIER_last:
3314 case OMPC_SCHEDULE_MODIFIER_unknown:
3315 break;
3316 }
3317 switch (M2) {
3318 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003319 Modifier = OMP_sch_modifier_monotonic;
3320 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003321 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003322 Modifier = OMP_sch_modifier_nonmonotonic;
3323 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003324 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003325 if (Schedule == OMP_sch_static_chunked)
3326 Schedule = OMP_sch_static_balanced_chunked;
3327 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003328 case OMPC_SCHEDULE_MODIFIER_last:
3329 case OMPC_SCHEDULE_MODIFIER_unknown:
3330 break;
3331 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003332 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003333}
3334
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003335void CGOpenMPRuntime::emitForDispatchInit(
3336 CodeGenFunction &CGF, SourceLocation Loc,
3337 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3338 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003339 if (!CGF.HaveInsertPoint())
3340 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003341 OpenMPSchedType Schedule = getRuntimeSchedule(
3342 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003343 assert(Ordered ||
3344 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003345 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3346 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003347 // Call __kmpc_dispatch_init(
3348 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3349 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3350 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003351
John McCall7f416cc2015-09-08 08:05:57 +00003352 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003353 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3354 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003355 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003356 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3357 CGF.Builder.getInt32(addMonoNonMonoModifier(
3358 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003359 DispatchValues.LB, // Lower
3360 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003361 CGF.Builder.getIntN(IVSize, 1), // Stride
3362 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003363 };
3364 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3365}
3366
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003367static void emitForStaticInitCall(
3368 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3369 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3370 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003371 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003372 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003373 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003374
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003375 assert(!Values.Ordered);
3376 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3377 Schedule == OMP_sch_static_balanced_chunked ||
3378 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3379 Schedule == OMP_dist_sch_static ||
3380 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003381
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003382 // Call __kmpc_for_static_init(
3383 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3384 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3385 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3386 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3387 llvm::Value *Chunk = Values.Chunk;
3388 if (Chunk == nullptr) {
3389 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3390 Schedule == OMP_dist_sch_static) &&
3391 "expected static non-chunked schedule");
3392 // If the Chunk was not specified in the clause - use default value 1.
3393 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3394 } else {
3395 assert((Schedule == OMP_sch_static_chunked ||
3396 Schedule == OMP_sch_static_balanced_chunked ||
3397 Schedule == OMP_ord_static_chunked ||
3398 Schedule == OMP_dist_sch_static_chunked) &&
3399 "expected static chunked schedule");
3400 }
3401 llvm::Value *Args[] = {
3402 UpdateLocation,
3403 ThreadId,
3404 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3405 M2)), // Schedule type
3406 Values.IL.getPointer(), // &isLastIter
3407 Values.LB.getPointer(), // &LB
3408 Values.UB.getPointer(), // &UB
3409 Values.ST.getPointer(), // &Stride
3410 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3411 Chunk // Chunk
3412 };
3413 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003414}
3415
John McCall7f416cc2015-09-08 08:05:57 +00003416void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3417 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003418 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003419 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003420 const StaticRTInput &Values) {
3421 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3422 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3423 assert(isOpenMPWorksharingDirective(DKind) &&
3424 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003425 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003426 isOpenMPLoopDirective(DKind)
3427 ? OMP_IDENT_WORK_LOOP
3428 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003429 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3430 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003431 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003432 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003433 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003434}
John McCall7f416cc2015-09-08 08:05:57 +00003435
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003436void CGOpenMPRuntime::emitDistributeStaticInit(
3437 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003438 OpenMPDistScheduleClauseKind SchedKind,
3439 const CGOpenMPRuntime::StaticRTInput &Values) {
3440 OpenMPSchedType ScheduleNum =
3441 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003442 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003443 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003444 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3445 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003446 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003447 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3448 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003449 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003450}
3451
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003452void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003453 SourceLocation Loc,
3454 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003455 if (!CGF.HaveInsertPoint())
3456 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003457 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003458 llvm::Value *Args[] = {
3459 emitUpdateLocation(CGF, Loc,
3460 isOpenMPDistributeDirective(DKind)
3461 ? OMP_IDENT_WORK_DISTRIBUTE
3462 : isOpenMPLoopDirective(DKind)
3463 ? OMP_IDENT_WORK_LOOP
3464 : OMP_IDENT_WORK_SECTIONS),
3465 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003466 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3467 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003468}
3469
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003470void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3471 SourceLocation Loc,
3472 unsigned IVSize,
3473 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003474 if (!CGF.HaveInsertPoint())
3475 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003476 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003477 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003478 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3479}
3480
Alexander Musman92bdaab2015-03-12 13:37:50 +00003481llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3482 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003483 bool IVSigned, Address IL,
3484 Address LB, Address UB,
3485 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003486 // Call __kmpc_dispatch_next(
3487 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3488 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3489 // kmp_int[32|64] *p_stride);
3490 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003491 emitUpdateLocation(CGF, Loc),
3492 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003493 IL.getPointer(), // &isLastIter
3494 LB.getPointer(), // &Lower
3495 UB.getPointer(), // &Upper
3496 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003497 };
3498 llvm::Value *Call =
3499 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3500 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003501 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003502 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003503}
3504
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003505void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3506 llvm::Value *NumThreads,
3507 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003508 if (!CGF.HaveInsertPoint())
3509 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003510 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3511 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003512 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003513 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003514 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3515 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003516}
3517
Alexey Bataev7f210c62015-06-18 13:40:03 +00003518void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3519 OpenMPProcBindClauseKind ProcBind,
3520 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003521 if (!CGF.HaveInsertPoint())
3522 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003523 // Constants for proc bind value accepted by the runtime.
3524 enum ProcBindTy {
3525 ProcBindFalse = 0,
3526 ProcBindTrue,
3527 ProcBindMaster,
3528 ProcBindClose,
3529 ProcBindSpread,
3530 ProcBindIntel,
3531 ProcBindDefault
3532 } RuntimeProcBind;
3533 switch (ProcBind) {
3534 case OMPC_PROC_BIND_master:
3535 RuntimeProcBind = ProcBindMaster;
3536 break;
3537 case OMPC_PROC_BIND_close:
3538 RuntimeProcBind = ProcBindClose;
3539 break;
3540 case OMPC_PROC_BIND_spread:
3541 RuntimeProcBind = ProcBindSpread;
3542 break;
3543 case OMPC_PROC_BIND_unknown:
3544 llvm_unreachable("Unsupported proc_bind value.");
3545 }
3546 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3547 llvm::Value *Args[] = {
3548 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3549 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3550 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3551}
3552
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003553void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3554 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003555 if (!CGF.HaveInsertPoint())
3556 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003557 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003558 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3559 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003560}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003561
Alexey Bataev62b63b12015-03-10 07:28:44 +00003562namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003563/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003564enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003565 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003566 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003567 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003568 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003569 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003570 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003571 /// Function with call of destructors for private variables.
3572 Data1,
3573 /// Task priority.
3574 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003575 /// (Taskloops only) Lower bound.
3576 KmpTaskTLowerBound,
3577 /// (Taskloops only) Upper bound.
3578 KmpTaskTUpperBound,
3579 /// (Taskloops only) Stride.
3580 KmpTaskTStride,
3581 /// (Taskloops only) Is last iteration flag.
3582 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003583 /// (Taskloops only) Reduction data.
3584 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003585};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003586} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003587
Samuel Antaoee8fb302016-01-06 13:42:12 +00003588bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003589 return OffloadEntriesTargetRegion.empty() &&
3590 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003591}
3592
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003593/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003594void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3595 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3596 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003597 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003598 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3599 "only required for the device "
3600 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003601 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003602 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003603 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003604 ++OffloadingEntriesNum;
3605}
3606
3607void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3608 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3609 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003610 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003611 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003612 // If we are emitting code for a target, the entry is already initialized,
3613 // only has to be registered.
3614 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003615 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3616 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3617 DiagnosticsEngine::Error,
3618 "Unable to find target region on line '%0' in the device code.");
3619 CGM.getDiags().Report(DiagID) << LineNum;
3620 return;
3621 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003622 auto &Entry =
3623 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003624 assert(Entry.isValid() && "Entry not initialized!");
3625 Entry.setAddress(Addr);
3626 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003627 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003628 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003629 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003630 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003631 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003632 }
3633}
3634
3635bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003636 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3637 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003638 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3639 if (PerDevice == OffloadEntriesTargetRegion.end())
3640 return false;
3641 auto PerFile = PerDevice->second.find(FileID);
3642 if (PerFile == PerDevice->second.end())
3643 return false;
3644 auto PerParentName = PerFile->second.find(ParentName);
3645 if (PerParentName == PerFile->second.end())
3646 return false;
3647 auto PerLine = PerParentName->second.find(LineNum);
3648 if (PerLine == PerParentName->second.end())
3649 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003650 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003651 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003652 return false;
3653 return true;
3654}
3655
3656void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3657 const OffloadTargetRegionEntryInfoActTy &Action) {
3658 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003659 for (const auto &D : OffloadEntriesTargetRegion)
3660 for (const auto &F : D.second)
3661 for (const auto &P : F.second)
3662 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003663 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003664}
3665
Alexey Bataev03f270c2018-03-30 18:31:07 +00003666void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3667 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3668 OMPTargetGlobalVarEntryKind Flags,
3669 unsigned Order) {
3670 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3671 "only required for the device "
3672 "code generation.");
3673 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3674 ++OffloadingEntriesNum;
3675}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003676
Alexey Bataev03f270c2018-03-30 18:31:07 +00003677void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3678 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3679 CharUnits VarSize,
3680 OMPTargetGlobalVarEntryKind Flags,
3681 llvm::GlobalValue::LinkageTypes Linkage) {
3682 if (CGM.getLangOpts().OpenMPIsDevice) {
3683 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3684 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3685 "Entry not initialized!");
3686 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3687 "Resetting with the new address.");
3688 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3689 return;
3690 Entry.setAddress(Addr);
3691 Entry.setVarSize(VarSize);
3692 Entry.setLinkage(Linkage);
3693 } else {
3694 if (hasDeviceGlobalVarEntryInfo(VarName))
3695 return;
3696 OffloadEntriesDeviceGlobalVar.try_emplace(
3697 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3698 ++OffloadingEntriesNum;
3699 }
3700}
3701
3702void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3703 actOnDeviceGlobalVarEntriesInfo(
3704 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3705 // Scan all target region entries and perform the provided action.
3706 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3707 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003708}
3709
3710llvm::Function *
3711CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003712 // If we don't have entries or if we are emitting code for the device, we
3713 // don't need to do anything.
3714 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3715 return nullptr;
3716
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003717 llvm::Module &M = CGM.getModule();
3718 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003719
3720 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003721 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003722
3723 // We should be creating an offloading descriptor only if there are devices
3724 // specified.
3725 assert(!Devices.empty() && "No OpenMP offloading devices??");
3726
3727 // Create the external variables that will point to the begin and end of the
3728 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003729 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003730 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003731 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003732 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003733 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003734 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003735 EntriesBeginName);
3736 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3737 auto *HostEntriesEnd =
3738 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3739 llvm::GlobalValue::ExternalLinkage,
3740 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003741
3742 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003743 auto *DeviceImageTy = cast<llvm::StructType>(
3744 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003745 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003746 ConstantArrayBuilder DeviceImagesEntries =
3747 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003748
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003749 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003750 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003751 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003752 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003753 M, CGM.Int8Ty, /*isConstant=*/true,
3754 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003755 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3756 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003757 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003758 M, CGM.Int8Ty, /*isConstant=*/true,
3759 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003760 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003761
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003762 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3763 HostEntriesEnd};
3764 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3765 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003766 }
3767
3768 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003769 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003770 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003771 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3772 CGM.getPointerAlign(),
3773 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003774 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003775
3776 // This is a Zero array to be used in the creation of the constant expressions
3777 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3778 llvm::Constant::getNullValue(CGM.Int32Ty)};
3779
3780 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003781 llvm::Constant *Data[] = {
3782 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3783 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3784 DeviceImages, Index),
3785 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003786 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003787 llvm::GlobalVariable *Desc = createConstantGlobalStruct(
Alexey Bataev18fa2322018-05-02 14:20:50 +00003788 CGM, getTgtBinaryDescriptorQTy(), Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003789
3790 // Emit code to register or unregister the descriptor at execution
3791 // startup or closing, respectively.
3792
Alexey Bataev03f270c2018-03-30 18:31:07 +00003793 llvm::Function *UnRegFn;
3794 {
3795 FunctionArgList Args;
3796 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3797 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003798
Alexey Bataev03f270c2018-03-30 18:31:07 +00003799 CodeGenFunction CGF(CGM);
3800 // Disable debug info for global (de-)initializer because they are not part
3801 // of some particular construct.
3802 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003803 const auto &FI =
3804 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3805 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003806 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3807 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003808 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3809 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3810 Desc);
3811 CGF.FinishFunction();
3812 }
3813 llvm::Function *RegFn;
3814 {
3815 CodeGenFunction CGF(CGM);
3816 // Disable debug info for global (de-)initializer because they are not part
3817 // of some particular construct.
3818 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003819 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003820 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003821 std::string Descriptor = getName({"omp_offloading", "descriptor_reg"});
3822 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003823 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3824 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3825 // Create a variable to drive the registration and unregistration of the
3826 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3827 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3828 SourceLocation(), nullptr, C.CharTy,
3829 ImplicitParamDecl::Other);
3830 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3831 CGF.FinishFunction();
3832 }
George Rokos29d0f002017-05-27 03:03:13 +00003833 if (CGM.supportsCOMDAT()) {
3834 // It is sufficient to call registration function only once, so create a
3835 // COMDAT group for registration/unregistration functions and associated
3836 // data. That would reduce startup time and code size. Registration
3837 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003838 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003839 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3840 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3841 RegFn->setComdat(ComdatKey);
3842 UnRegFn->setComdat(ComdatKey);
3843 DeviceImages->setComdat(ComdatKey);
3844 Desc->setComdat(ComdatKey);
3845 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003846 return RegFn;
3847}
3848
Alexey Bataev03f270c2018-03-30 18:31:07 +00003849void CGOpenMPRuntime::createOffloadEntry(
3850 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3851 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003852 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003853 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003854 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003855
3856 // Create constant string with the name.
3857 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3858
Alexey Bataev18fa2322018-05-02 14:20:50 +00003859 std::string StringName = getName({"omp_offloading", "entry_name"});
3860 auto *Str = new llvm::GlobalVariable(
3861 M, StrPtrInit->getType(), /*isConstant=*/true,
3862 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003863 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003864
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003865 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3866 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3867 llvm::ConstantInt::get(CGM.SizeTy, Size),
3868 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3869 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003870 std::string EntryName = getName({"omp_offloading", "entry", ""});
Alexey Bataev9a700172018-05-08 14:16:57 +00003871 llvm::GlobalVariable *Entry = createConstantGlobalStruct(
3872 CGM, getTgtOffloadEntryQTy(), Data, Twine(EntryName).concat(Name),
3873 llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003874
3875 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003876 std::string Section = getName({"omp_offloading", "entries"});
3877 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003878}
3879
3880void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3881 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003882 // can easily figure out what to emit. The produced metadata looks like
3883 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003884 //
3885 // !omp_offload.info = !{!1, ...}
3886 //
3887 // Right now we only generate metadata for function that contain target
3888 // regions.
3889
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003890 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003891 if (OffloadEntriesInfoManager.empty())
3892 return;
3893
3894 llvm::Module &M = CGM.getModule();
3895 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003896 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003897 OrderedEntries(OffloadEntriesInfoManager.size());
3898
Simon Pilgrim2c518802017-03-30 14:13:19 +00003899 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003900 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003901 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003902 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003903 };
3904
Alexey Bataev03f270c2018-03-30 18:31:07 +00003905 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3906
3907 // Create the offloading info metadata node.
3908 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003909
3910 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003911 auto &&TargetRegionMetadataEmitter =
3912 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3913 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3914 unsigned Line,
3915 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3916 // Generate metadata for target regions. Each entry of this metadata
3917 // contains:
3918 // - Entry 0 -> Kind of this type of metadata (0).
3919 // - Entry 1 -> Device ID of the file where the entry was identified.
3920 // - Entry 2 -> File ID of the file where the entry was identified.
3921 // - Entry 3 -> Mangled name of the function where the entry was
3922 // identified.
3923 // - Entry 4 -> Line in the file where the entry was identified.
3924 // - Entry 5 -> Order the entry was created.
3925 // The first element of the metadata node is the kind.
3926 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3927 GetMDInt(FileID), GetMDString(ParentName),
3928 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003929
Alexey Bataev03f270c2018-03-30 18:31:07 +00003930 // Save this entry in the right position of the ordered entries array.
3931 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003932
Alexey Bataev03f270c2018-03-30 18:31:07 +00003933 // Add metadata to the named metadata node.
3934 MD->addOperand(llvm::MDNode::get(C, Ops));
3935 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003936
3937 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3938 TargetRegionMetadataEmitter);
3939
Alexey Bataev03f270c2018-03-30 18:31:07 +00003940 // Create function that emits metadata for each device global variable entry;
3941 auto &&DeviceGlobalVarMetadataEmitter =
3942 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3943 MD](StringRef MangledName,
3944 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3945 &E) {
3946 // Generate metadata for global variables. Each entry of this metadata
3947 // contains:
3948 // - Entry 0 -> Kind of this type of metadata (1).
3949 // - Entry 1 -> Mangled name of the variable.
3950 // - Entry 2 -> Declare target kind.
3951 // - Entry 3 -> Order the entry was created.
3952 // The first element of the metadata node is the kind.
3953 llvm::Metadata *Ops[] = {
3954 GetMDInt(E.getKind()), GetMDString(MangledName),
3955 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3956
3957 // Save this entry in the right position of the ordered entries array.
3958 OrderedEntries[E.getOrder()] = &E;
3959
3960 // Add metadata to the named metadata node.
3961 MD->addOperand(llvm::MDNode::get(C, Ops));
3962 };
3963
3964 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3965 DeviceGlobalVarMetadataEmitter);
3966
3967 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003968 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003969 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003970 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3971 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003972 if (!CE->getID() || !CE->getAddress()) {
3973 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3974 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00003975 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003976 "address or the ID is invalid.");
3977 CGM.getDiags().Report(DiagID);
3978 continue;
3979 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00003980 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00003981 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3982 } else if (const auto *CE =
3983 dyn_cast<OffloadEntriesInfoManagerTy::
3984 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00003985 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
3986 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
3987 CE->getFlags());
3988 switch (Flags) {
3989 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
3990 if (!CE->getAddress()) {
3991 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3992 DiagnosticsEngine::Error,
3993 "Offloading entry for declare target variable is incorrect: the "
3994 "address is invalid.");
3995 CGM.getDiags().Report(DiagID);
3996 continue;
3997 }
3998 break;
3999 }
4000 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4001 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4002 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4003 "Declaret target link address is set.");
4004 if (CGM.getLangOpts().OpenMPIsDevice)
4005 continue;
4006 if (!CE->getAddress()) {
4007 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4008 DiagnosticsEngine::Error,
4009 "Offloading entry for declare target variable is incorrect: the "
4010 "address is invalid.");
4011 CGM.getDiags().Report(DiagID);
4012 continue;
4013 }
4014 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004015 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004016 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004017 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004018 CE->getLinkage());
4019 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004020 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004021 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004022 }
4023}
4024
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004025/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004026/// metadata.
4027void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4028 // If we are in target mode, load the metadata from the host IR. This code has
4029 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4030
4031 if (!CGM.getLangOpts().OpenMPIsDevice)
4032 return;
4033
4034 if (CGM.getLangOpts().OMPHostIRFile.empty())
4035 return;
4036
4037 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004038 if (auto EC = Buf.getError()) {
4039 CGM.getDiags().Report(diag::err_cannot_open_file)
4040 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004041 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004042 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004043
4044 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004045 auto ME = expectedToErrorOrAndEmitErrors(
4046 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004047
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004048 if (auto EC = ME.getError()) {
4049 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4050 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4051 CGM.getDiags().Report(DiagID)
4052 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004053 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004054 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004055
4056 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4057 if (!MD)
4058 return;
4059
George Burgess IV00f70bd2018-03-01 05:43:23 +00004060 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004061 auto &&GetMDInt = [MN](unsigned Idx) {
4062 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004063 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4064 };
4065
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004066 auto &&GetMDString = [MN](unsigned Idx) {
4067 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004068 return V->getString();
4069 };
4070
Alexey Bataev03f270c2018-03-30 18:31:07 +00004071 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004072 default:
4073 llvm_unreachable("Unexpected metadata!");
4074 break;
4075 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004076 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004077 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004078 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4079 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4080 /*Order=*/GetMDInt(5));
4081 break;
4082 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4083 OffloadingEntryInfoDeviceGlobalVar:
4084 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4085 /*MangledName=*/GetMDString(1),
4086 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4087 /*Flags=*/GetMDInt(2)),
4088 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004089 break;
4090 }
4091 }
4092}
4093
Alexey Bataev62b63b12015-03-10 07:28:44 +00004094void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4095 if (!KmpRoutineEntryPtrTy) {
4096 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004097 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004098 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4099 FunctionProtoType::ExtProtoInfo EPI;
4100 KmpRoutineEntryPtrQTy = C.getPointerType(
4101 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4102 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4103 }
4104}
4105
Samuel Antaoee8fb302016-01-06 13:42:12 +00004106QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004107 // Make sure the type of the entry is already created. This is the type we
4108 // have to create:
4109 // struct __tgt_offload_entry{
4110 // void *addr; // Pointer to the offload entry info.
4111 // // (function or global)
4112 // char *name; // Name of the function or global.
4113 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004114 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4115 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004116 // };
4117 if (TgtOffloadEntryQTy.isNull()) {
4118 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004119 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004120 RD->startDefinition();
4121 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4122 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4123 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004124 addFieldToRecordDecl(
4125 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4126 addFieldToRecordDecl(
4127 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004128 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004129 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004130 TgtOffloadEntryQTy = C.getRecordType(RD);
4131 }
4132 return TgtOffloadEntryQTy;
4133}
4134
4135QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4136 // These are the types we need to build:
4137 // struct __tgt_device_image{
4138 // void *ImageStart; // Pointer to the target code start.
4139 // void *ImageEnd; // Pointer to the target code end.
4140 // // We also add the host entries to the device image, as it may be useful
4141 // // for the target runtime to have access to that information.
4142 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4143 // // the entries.
4144 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4145 // // entries (non inclusive).
4146 // };
4147 if (TgtDeviceImageQTy.isNull()) {
4148 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004149 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004150 RD->startDefinition();
4151 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4152 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4153 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4154 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4155 RD->completeDefinition();
4156 TgtDeviceImageQTy = C.getRecordType(RD);
4157 }
4158 return TgtDeviceImageQTy;
4159}
4160
4161QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4162 // struct __tgt_bin_desc{
4163 // int32_t NumDevices; // Number of devices supported.
4164 // __tgt_device_image *DeviceImages; // Arrays of device images
4165 // // (one per device).
4166 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4167 // // entries.
4168 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4169 // // entries (non inclusive).
4170 // };
4171 if (TgtBinaryDescriptorQTy.isNull()) {
4172 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004173 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004174 RD->startDefinition();
4175 addFieldToRecordDecl(
4176 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4177 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4178 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4179 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4180 RD->completeDefinition();
4181 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4182 }
4183 return TgtBinaryDescriptorQTy;
4184}
4185
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004186namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004187struct PrivateHelpersTy {
4188 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4189 const VarDecl *PrivateElemInit)
4190 : Original(Original), PrivateCopy(PrivateCopy),
4191 PrivateElemInit(PrivateElemInit) {}
4192 const VarDecl *Original;
4193 const VarDecl *PrivateCopy;
4194 const VarDecl *PrivateElemInit;
4195};
4196typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004197} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004198
Alexey Bataev9e034042015-05-05 04:05:12 +00004199static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004200createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004201 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004202 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004203 // Build struct .kmp_privates_t. {
4204 // /* private vars */
4205 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004206 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004207 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004208 for (const auto &Pair : Privates) {
4209 const VarDecl *VD = Pair.second.Original;
4210 QualType Type = VD->getType().getNonReferenceType();
4211 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004212 if (VD->hasAttrs()) {
4213 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4214 E(VD->getAttrs().end());
4215 I != E; ++I)
4216 FD->addAttr(*I);
4217 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004218 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004219 RD->completeDefinition();
4220 return RD;
4221 }
4222 return nullptr;
4223}
4224
Alexey Bataev9e034042015-05-05 04:05:12 +00004225static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004226createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4227 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004228 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004229 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004230 // Build struct kmp_task_t {
4231 // void * shareds;
4232 // kmp_routine_entry_t routine;
4233 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004234 // kmp_cmplrdata_t data1;
4235 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004236 // For taskloops additional fields:
4237 // kmp_uint64 lb;
4238 // kmp_uint64 ub;
4239 // kmp_int64 st;
4240 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004241 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004242 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004243 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004244 UD->startDefinition();
4245 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4246 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4247 UD->completeDefinition();
4248 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004249 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004250 RD->startDefinition();
4251 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4252 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4253 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004254 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4255 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004256 if (isOpenMPTaskLoopDirective(Kind)) {
4257 QualType KmpUInt64Ty =
4258 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4259 QualType KmpInt64Ty =
4260 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4261 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4262 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4263 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4264 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004265 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004266 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004267 RD->completeDefinition();
4268 return RD;
4269}
4270
4271static RecordDecl *
4272createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004273 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004274 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004275 // Build struct kmp_task_t_with_privates {
4276 // kmp_task_t task_data;
4277 // .kmp_privates_t. privates;
4278 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004279 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004280 RD->startDefinition();
4281 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004282 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004283 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004284 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004285 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004286}
4287
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004288/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004289/// argument.
4290/// \code
4291/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004292/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004293/// For taskloops:
4294/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004295/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004296/// return 0;
4297/// }
4298/// \endcode
4299static llvm::Value *
4300emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004301 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4302 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004303 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004304 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4305 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004306 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004307 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004308 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4309 ImplicitParamDecl::Other);
4310 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4311 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4312 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004313 Args.push_back(&GtidArg);
4314 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004315 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004316 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004317 llvm::FunctionType *TaskEntryTy =
4318 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004319 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4320 auto *TaskEntry = llvm::Function::Create(
4321 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004322 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004323 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004324 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004325 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4326 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004327
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004328 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004329 // tt,
4330 // For taskloops:
4331 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4332 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004333 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004334 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004335 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4336 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4337 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004338 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004339 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004340 LValue Base =
4341 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004342 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004343 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004344 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4345 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004346
4347 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004348 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4349 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004350 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004351 CGF.ConvertTypeForMem(SharedsPtrTy));
4352
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004353 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4354 llvm::Value *PrivatesParam;
4355 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004356 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004357 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004358 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004359 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004360 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004361 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004362
Alexey Bataev7292c292016-04-25 12:22:29 +00004363 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4364 TaskPrivatesMap,
4365 CGF.Builder
4366 .CreatePointerBitCastOrAddrSpaceCast(
4367 TDBase.getAddress(), CGF.VoidPtrTy)
4368 .getPointer()};
4369 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4370 std::end(CommonArgs));
4371 if (isOpenMPTaskLoopDirective(Kind)) {
4372 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004373 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4374 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004375 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004376 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4377 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004378 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004379 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4380 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004381 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004382 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4383 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004384 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004385 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4386 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004387 CallArgs.push_back(LBParam);
4388 CallArgs.push_back(UBParam);
4389 CallArgs.push_back(StParam);
4390 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004391 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004392 }
4393 CallArgs.push_back(SharedsParam);
4394
Alexey Bataev3c595a62017-08-14 15:01:03 +00004395 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4396 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004397 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4398 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004399 CGF.FinishFunction();
4400 return TaskEntry;
4401}
4402
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004403static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4404 SourceLocation Loc,
4405 QualType KmpInt32Ty,
4406 QualType KmpTaskTWithPrivatesPtrQTy,
4407 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004408 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004409 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004410 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4411 ImplicitParamDecl::Other);
4412 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4413 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4414 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004415 Args.push_back(&GtidArg);
4416 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004417 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004418 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004419 llvm::FunctionType *DestructorFnTy =
4420 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004421 std::string Name =
4422 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004423 auto *DestructorFn =
4424 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004425 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004426 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004427 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004428 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004429 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004430 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004431 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004432
Alexey Bataev31300ed2016-02-04 11:27:03 +00004433 LValue Base = CGF.EmitLoadOfPointerLValue(
4434 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4435 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004436 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004437 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4438 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004439 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004440 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004441 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004442 if (QualType::DestructionKind DtorKind =
4443 Field->getType().isDestructedType()) {
4444 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004445 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4446 }
4447 }
4448 CGF.FinishFunction();
4449 return DestructorFn;
4450}
4451
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004452/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004453/// firstprivate variables.
4454/// \code
4455/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4456/// **noalias priv1,..., <tyn> **noalias privn) {
4457/// *priv1 = &.privates.priv1;
4458/// ...;
4459/// *privn = &.privates.privn;
4460/// }
4461/// \endcode
4462static llvm::Value *
4463emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004464 ArrayRef<const Expr *> PrivateVars,
4465 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004466 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004467 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004468 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004469 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004470 FunctionArgList Args;
4471 ImplicitParamDecl TaskPrivatesArg(
4472 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004473 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4474 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004475 Args.push_back(&TaskPrivatesArg);
4476 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4477 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004478 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004479 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004480 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4481 C.getPointerType(C.getPointerType(E->getType()))
4482 .withConst()
4483 .withRestrict(),
4484 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004485 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004486 PrivateVarsPos[VD] = Counter;
4487 ++Counter;
4488 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004489 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004490 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004491 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4492 C.getPointerType(C.getPointerType(E->getType()))
4493 .withConst()
4494 .withRestrict(),
4495 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004496 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004497 PrivateVarsPos[VD] = Counter;
4498 ++Counter;
4499 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004500 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004501 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004502 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4503 C.getPointerType(C.getPointerType(E->getType()))
4504 .withConst()
4505 .withRestrict(),
4506 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004507 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004508 PrivateVarsPos[VD] = Counter;
4509 ++Counter;
4510 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004511 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004512 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004513 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004514 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004515 std::string Name =
4516 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004517 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004518 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4519 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004520 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004521 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004522 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004523 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004524 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004525 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004526 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004527 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004528
4529 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004530 LValue Base = CGF.EmitLoadOfPointerLValue(
4531 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4532 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004533 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004534 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004535 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4536 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4537 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4538 LValue RefLVal =
4539 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4540 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004541 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004542 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004543 ++Counter;
4544 }
4545 CGF.FinishFunction();
4546 return TaskPrivatesMap;
4547}
4548
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004549static bool stable_sort_comparator(const PrivateDataTy P1,
4550 const PrivateDataTy P2) {
4551 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004552}
4553
Alexey Bataevf93095a2016-05-05 08:46:22 +00004554/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004555static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004556 const OMPExecutableDirective &D,
4557 Address KmpTaskSharedsPtr, LValue TDBase,
4558 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4559 QualType SharedsTy, QualType SharedsPtrTy,
4560 const OMPTaskDataTy &Data,
4561 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004562 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004563 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4564 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004565 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4566 ? OMPD_taskloop
4567 : OMPD_task;
4568 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4569 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004570 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004571 bool IsTargetTask =
4572 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4573 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4574 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4575 // PointersArray and SizesArray. The original variables for these arrays are
4576 // not captured and we get their addresses explicitly.
4577 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004578 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004579 SrcBase = CGF.MakeAddrLValue(
4580 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4581 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4582 SharedsTy);
4583 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004584 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004585 for (const PrivateDataTy &Pair : Privates) {
4586 const VarDecl *VD = Pair.second.PrivateCopy;
4587 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004588 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4589 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004590 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004591 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4592 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004593 // Check if the variable is the target-based BasePointersArray,
4594 // PointersArray or SizesArray.
4595 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004596 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004597 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004598 if (IsTargetTask && !SharedField) {
4599 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4600 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4601 cast<CapturedDecl>(OriginalVD->getDeclContext())
4602 ->getNumParams() == 0 &&
4603 isa<TranslationUnitDecl>(
4604 cast<CapturedDecl>(OriginalVD->getDeclContext())
4605 ->getDeclContext()) &&
4606 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004607 SharedRefLValue =
4608 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4609 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004610 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4611 SharedRefLValue = CGF.MakeAddrLValue(
4612 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4613 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4614 SharedRefLValue.getTBAAInfo());
4615 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004616 if (Type->isArrayType()) {
4617 // Initialize firstprivate array.
4618 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4619 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004620 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004621 } else {
4622 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004623 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004624 CGF.EmitOMPAggregateAssign(
4625 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4626 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4627 Address SrcElement) {
4628 // Clean up any temporaries needed by the initialization.
4629 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4630 InitScope.addPrivate(
4631 Elem, [SrcElement]() -> Address { return SrcElement; });
4632 (void)InitScope.Privatize();
4633 // Emit initialization for single element.
4634 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4635 CGF, &CapturesInfo);
4636 CGF.EmitAnyExprToMem(Init, DestElement,
4637 Init->getType().getQualifiers(),
4638 /*IsInitializer=*/false);
4639 });
4640 }
4641 } else {
4642 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4643 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4644 return SharedRefLValue.getAddress();
4645 });
4646 (void)InitScope.Privatize();
4647 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4648 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4649 /*capturedByInit=*/false);
4650 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004651 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004652 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004653 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004654 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004655 ++FI;
4656 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004657}
4658
4659/// Check if duplication function is required for taskloops.
4660static bool checkInitIsRequired(CodeGenFunction &CGF,
4661 ArrayRef<PrivateDataTy> Privates) {
4662 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004663 for (const PrivateDataTy &Pair : Privates) {
4664 const VarDecl *VD = Pair.second.PrivateCopy;
4665 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004666 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4667 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004668 if (InitRequired)
4669 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004670 }
4671 return InitRequired;
4672}
4673
4674
4675/// Emit task_dup function (for initialization of
4676/// private/firstprivate/lastprivate vars and last_iter flag)
4677/// \code
4678/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4679/// lastpriv) {
4680/// // setup lastprivate flag
4681/// task_dst->last = lastpriv;
4682/// // could be constructor calls here...
4683/// }
4684/// \endcode
4685static llvm::Value *
4686emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4687 const OMPExecutableDirective &D,
4688 QualType KmpTaskTWithPrivatesPtrQTy,
4689 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4690 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4691 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4692 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004693 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004694 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004695 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4696 KmpTaskTWithPrivatesPtrQTy,
4697 ImplicitParamDecl::Other);
4698 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4699 KmpTaskTWithPrivatesPtrQTy,
4700 ImplicitParamDecl::Other);
4701 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4702 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004703 Args.push_back(&DstArg);
4704 Args.push_back(&SrcArg);
4705 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004706 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004707 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004708 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004709 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4710 auto *TaskDup = llvm::Function::Create(
4711 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004712 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004713 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004714 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004715 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4716 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004717
4718 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4719 CGF.GetAddrOfLocalVar(&DstArg),
4720 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4721 // task_dst->liter = lastpriv;
4722 if (WithLastIter) {
4723 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4724 LValue Base = CGF.EmitLValueForField(
4725 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4726 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4727 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4728 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4729 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4730 }
4731
4732 // Emit initial values for private copies (if any).
4733 assert(!Privates.empty());
4734 Address KmpTaskSharedsPtr = Address::invalid();
4735 if (!Data.FirstprivateVars.empty()) {
4736 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4737 CGF.GetAddrOfLocalVar(&SrcArg),
4738 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4739 LValue Base = CGF.EmitLValueForField(
4740 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4741 KmpTaskSharedsPtr = Address(
4742 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4743 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4744 KmpTaskTShareds)),
4745 Loc),
4746 CGF.getNaturalTypeAlignment(SharedsTy));
4747 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004748 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4749 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004750 CGF.FinishFunction();
4751 return TaskDup;
4752}
4753
Alexey Bataev8a831592016-05-10 10:36:51 +00004754/// Checks if destructor function is required to be generated.
4755/// \return true if cleanups are required, false otherwise.
4756static bool
4757checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4758 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004759 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4760 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4761 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004762 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4763 if (NeedsCleanup)
4764 break;
4765 }
4766 return NeedsCleanup;
4767}
4768
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004769CGOpenMPRuntime::TaskResultTy
4770CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4771 const OMPExecutableDirective &D,
4772 llvm::Value *TaskFunction, QualType SharedsTy,
4773 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004774 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004775 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004776 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004777 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004778 for (const Expr *E : Data.PrivateVars) {
4779 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004780 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004781 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004782 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004783 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004784 ++I;
4785 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004786 I = Data.FirstprivateCopies.begin();
4787 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004788 for (const Expr *E : Data.FirstprivateVars) {
4789 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004790 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004791 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004792 PrivateHelpersTy(
4793 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004794 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004795 ++I;
4796 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004797 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004798 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004799 for (const Expr *E : Data.LastprivateVars) {
4800 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004801 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004802 C.getDeclAlign(VD),
4803 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004804 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004805 ++I;
4806 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004807 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004808 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004809 // Build type kmp_routine_entry_t (if not built yet).
4810 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004811 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004812 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4813 if (SavedKmpTaskloopTQTy.isNull()) {
4814 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4815 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4816 }
4817 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004818 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004819 assert((D.getDirectiveKind() == OMPD_task ||
4820 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4821 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4822 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004823 if (SavedKmpTaskTQTy.isNull()) {
4824 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4825 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4826 }
4827 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004828 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004829 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004830 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004831 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004832 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004833 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004834 QualType KmpTaskTWithPrivatesPtrQTy =
4835 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004836 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4837 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4838 KmpTaskTWithPrivatesTy->getPointerTo();
4839 llvm::Value *KmpTaskTWithPrivatesTySize =
4840 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004841 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4842
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004843 // Emit initial values for private copies (if any).
4844 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004845 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004846 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004847 if (!Privates.empty()) {
4848 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004849 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4850 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4851 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004852 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4853 TaskPrivatesMap, TaskPrivatesMapTy);
4854 } else {
4855 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4856 cast<llvm::PointerType>(TaskPrivatesMapTy));
4857 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004858 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4859 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004860 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004861 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4862 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4863 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004864
4865 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4866 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4867 // kmp_routine_entry_t *task_entry);
4868 // Task flags. Format is taken from
4869 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4870 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004871 enum {
4872 TiedFlag = 0x1,
4873 FinalFlag = 0x2,
4874 DestructorsFlag = 0x8,
4875 PriorityFlag = 0x20
4876 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004877 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004878 bool NeedsCleanup = false;
4879 if (!Privates.empty()) {
4880 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4881 if (NeedsCleanup)
4882 Flags = Flags | DestructorsFlag;
4883 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004884 if (Data.Priority.getInt())
4885 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004886 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004887 Data.Final.getPointer()
4888 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004889 CGF.Builder.getInt32(FinalFlag),
4890 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004891 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004892 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004893 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004894 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4895 getThreadID(CGF, Loc), TaskFlags,
4896 KmpTaskTWithPrivatesTySize, SharedsSize,
4897 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4898 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004899 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004900 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004901 llvm::Value *NewTaskNewTaskTTy =
4902 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4903 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004904 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4905 KmpTaskTWithPrivatesQTy);
4906 LValue TDBase =
4907 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004908 // Fill the data in the resulting kmp_task_t record.
4909 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004910 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004911 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004912 KmpTaskSharedsPtr =
4913 Address(CGF.EmitLoadOfScalar(
4914 CGF.EmitLValueForField(
4915 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4916 KmpTaskTShareds)),
4917 Loc),
4918 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004919 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4920 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004921 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004922 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004923 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004924 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004925 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004926 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4927 SharedsTy, SharedsPtrTy, Data, Privates,
4928 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004929 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4930 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4931 Result.TaskDupFn = emitTaskDupFunction(
4932 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4933 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4934 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004935 }
4936 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004937 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4938 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004939 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004940 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004941 const RecordDecl *KmpCmplrdataUD =
4942 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004943 if (NeedsCleanup) {
4944 llvm::Value *DestructorFn = emitDestructorsFunction(
4945 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4946 KmpTaskTWithPrivatesQTy);
4947 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4948 LValue DestructorsLV = CGF.EmitLValueForField(
4949 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4950 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4951 DestructorFn, KmpRoutineEntryPtrTy),
4952 DestructorsLV);
4953 }
4954 // Set priority.
4955 if (Data.Priority.getInt()) {
4956 LValue Data2LV = CGF.EmitLValueForField(
4957 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4958 LValue PriorityLV = CGF.EmitLValueForField(
4959 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4960 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4961 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004962 Result.NewTask = NewTask;
4963 Result.TaskEntry = TaskEntry;
4964 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4965 Result.TDBase = TDBase;
4966 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4967 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004968}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004969
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004970void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4971 const OMPExecutableDirective &D,
4972 llvm::Value *TaskFunction,
4973 QualType SharedsTy, Address Shareds,
4974 const Expr *IfCond,
4975 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004976 if (!CGF.HaveInsertPoint())
4977 return;
4978
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004979 TaskResultTy Result =
4980 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4981 llvm::Value *NewTask = Result.NewTask;
4982 llvm::Value *TaskEntry = Result.TaskEntry;
4983 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4984 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004985 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4986 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004987 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004988 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004989 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004990 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004991 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004992 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004993 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4994 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004995 QualType FlagsTy =
4996 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004997 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4998 if (KmpDependInfoTy.isNull()) {
4999 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5000 KmpDependInfoRD->startDefinition();
5001 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5002 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5003 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5004 KmpDependInfoRD->completeDefinition();
5005 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005006 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005007 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005008 }
John McCall7f416cc2015-09-08 08:05:57 +00005009 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005010 // Define type kmp_depend_info[<Dependences.size()>];
5011 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005012 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005013 ArrayType::Normal, /*IndexTypeQuals=*/0);
5014 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005015 DependenciesArray =
5016 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005017 for (unsigned I = 0; I < NumDependencies; ++I) {
5018 const Expr *E = Data.Dependences[I].second;
5019 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005020 llvm::Value *Size;
5021 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005022 if (const auto *ASE =
5023 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005024 LValue UpAddrLVal =
5025 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5026 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005027 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005028 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005029 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005030 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5031 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005032 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005033 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005034 }
5035 LValue Base = CGF.MakeAddrLValue(
5036 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005037 KmpDependInfoTy);
5038 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005039 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005040 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005041 CGF.EmitStoreOfScalar(
5042 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5043 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005044 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005045 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005046 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5047 CGF.EmitStoreOfScalar(Size, LenLVal);
5048 // deps[i].flags = <Dependences[i].first>;
5049 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005050 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005051 case OMPC_DEPEND_in:
5052 DepKind = DepIn;
5053 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005054 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005055 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005056 case OMPC_DEPEND_inout:
5057 DepKind = DepInOut;
5058 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005059 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005060 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005061 case OMPC_DEPEND_unknown:
5062 llvm_unreachable("Unknown task dependence type");
5063 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005064 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005065 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5066 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5067 FlagsLVal);
5068 }
John McCall7f416cc2015-09-08 08:05:57 +00005069 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5070 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005071 CGF.VoidPtrTy);
5072 }
5073
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005074 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005075 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005076 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5077 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5078 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5079 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005080 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5081 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005082 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5083 llvm::Value *DepTaskArgs[7];
5084 if (NumDependencies) {
5085 DepTaskArgs[0] = UpLoc;
5086 DepTaskArgs[1] = ThreadID;
5087 DepTaskArgs[2] = NewTask;
5088 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5089 DepTaskArgs[4] = DependenciesArray.getPointer();
5090 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5091 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5092 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005093 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5094 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005095 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005096 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005097 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005098 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005099 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5100 }
John McCall7f416cc2015-09-08 08:05:57 +00005101 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005102 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005103 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005104 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005105 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005106 TaskArgs);
5107 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005108 // Check if parent region is untied and build return for untied task;
5109 if (auto *Region =
5110 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5111 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005112 };
John McCall7f416cc2015-09-08 08:05:57 +00005113
5114 llvm::Value *DepWaitTaskArgs[6];
5115 if (NumDependencies) {
5116 DepWaitTaskArgs[0] = UpLoc;
5117 DepWaitTaskArgs[1] = ThreadID;
5118 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5119 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5120 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5121 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5122 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005123 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005124 NumDependencies, &DepWaitTaskArgs,
5125 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005126 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005127 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5128 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5129 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5130 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5131 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005132 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005133 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005134 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005135 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005136 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5137 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005138 Action.Enter(CGF);
5139 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005140 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005141 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005142 };
5143
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005144 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5145 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005146 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5147 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005148 RegionCodeGenTy RCG(CodeGen);
5149 CommonActionTy Action(
5150 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5151 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5152 RCG.setAction(Action);
5153 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005154 };
John McCall7f416cc2015-09-08 08:05:57 +00005155
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005156 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005157 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005158 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005159 RegionCodeGenTy ThenRCG(ThenCodeGen);
5160 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005161 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005162}
5163
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005164void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5165 const OMPLoopDirective &D,
5166 llvm::Value *TaskFunction,
5167 QualType SharedsTy, Address Shareds,
5168 const Expr *IfCond,
5169 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005170 if (!CGF.HaveInsertPoint())
5171 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005172 TaskResultTy Result =
5173 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005174 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005175 // libcall.
5176 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5177 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5178 // sched, kmp_uint64 grainsize, void *task_dup);
5179 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5180 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5181 llvm::Value *IfVal;
5182 if (IfCond) {
5183 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5184 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005185 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005186 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005187 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005188
5189 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005190 Result.TDBase,
5191 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005192 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005193 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5194 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5195 /*IsInitializer=*/true);
5196 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005197 Result.TDBase,
5198 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005199 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005200 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5201 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5202 /*IsInitializer=*/true);
5203 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005204 Result.TDBase,
5205 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005206 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005207 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5208 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5209 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005210 // Store reductions address.
5211 LValue RedLVal = CGF.EmitLValueForField(
5212 Result.TDBase,
5213 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005214 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005215 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005216 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005217 CGF.EmitNullInitialization(RedLVal.getAddress(),
5218 CGF.getContext().VoidPtrTy);
5219 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005220 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005221 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005222 UpLoc,
5223 ThreadID,
5224 Result.NewTask,
5225 IfVal,
5226 LBLVal.getPointer(),
5227 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005228 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00005229 llvm::ConstantInt::getNullValue(
5230 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005231 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005232 CGF.IntTy, Data.Schedule.getPointer()
5233 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005234 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005235 Data.Schedule.getPointer()
5236 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005237 /*isSigned=*/false)
5238 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005239 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5240 Result.TaskDupFn, CGF.VoidPtrTy)
5241 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005242 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5243}
5244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005245/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005246/// array sections) LHS op = RHS.
5247/// \param Type Type of array.
5248/// \param LHSVar Variable on the left side of the reduction operation
5249/// (references element of array in original variable).
5250/// \param RHSVar Variable on the right side of the reduction operation
5251/// (references element of array in original variable).
5252/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5253/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005254static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005255 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5256 const VarDecl *RHSVar,
5257 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5258 const Expr *, const Expr *)> &RedOpGen,
5259 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5260 const Expr *UpExpr = nullptr) {
5261 // Perform element-by-element initialization.
5262 QualType ElementTy;
5263 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5264 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5265
5266 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005267 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5268 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005269
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005270 llvm::Value *RHSBegin = RHSAddr.getPointer();
5271 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005272 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005273 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005274 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005275 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5276 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5277 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005278 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5279 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5280
5281 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005282 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005283 CGF.EmitBlock(BodyBB);
5284
5285 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5286
5287 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5288 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5289 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5290 Address RHSElementCurrent =
5291 Address(RHSElementPHI,
5292 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5293
5294 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5295 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5296 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5297 Address LHSElementCurrent =
5298 Address(LHSElementPHI,
5299 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5300
5301 // Emit copy.
5302 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005303 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5304 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005305 Scope.Privatize();
5306 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5307 Scope.ForceCleanup();
5308
5309 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005310 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005311 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005312 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005313 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5314 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005315 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005316 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5317 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5318 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5319 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5320
5321 // Done.
5322 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5323}
5324
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005325/// Emit reduction combiner. If the combiner is a simple expression emit it as
5326/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5327/// UDR combiner function.
5328static void emitReductionCombiner(CodeGenFunction &CGF,
5329 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005330 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5331 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5332 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005333 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005334 if (const auto *DRD =
5335 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005336 std::pair<llvm::Function *, llvm::Function *> Reduction =
5337 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5338 RValue Func = RValue::get(Reduction.first);
5339 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5340 CGF.EmitIgnoredExpr(ReductionOp);
5341 return;
5342 }
5343 CGF.EmitIgnoredExpr(ReductionOp);
5344}
5345
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005346llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005347 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5348 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5349 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005350 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005351
5352 // void reduction_func(void *LHSArg, void *RHSArg);
5353 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005354 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5355 ImplicitParamDecl::Other);
5356 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5357 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005358 Args.push_back(&LHSArg);
5359 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005360 const auto &CGFI =
5361 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005362 std::string Name = getName({"omp", "reduction", "reduction_func"});
5363 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5364 llvm::GlobalValue::InternalLinkage, Name,
5365 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005366 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005367 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005368 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005369 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005370
5371 // Dst = (void*[n])(LHSArg);
5372 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005373 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5374 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5375 ArgsType), CGF.getPointerAlign());
5376 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5377 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5378 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005379
5380 // ...
5381 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5382 // ...
5383 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005384 auto IPriv = Privates.begin();
5385 unsigned Idx = 0;
5386 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005387 const auto *RHSVar =
5388 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5389 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005390 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005391 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005392 const auto *LHSVar =
5393 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5394 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005395 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005396 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005397 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005398 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005399 // Get array size and emit VLA type.
5400 ++Idx;
5401 Address Elem =
5402 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5403 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005404 const VariableArrayType *VLA =
5405 CGF.getContext().getAsVariableArrayType(PrivTy);
5406 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005407 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005408 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005409 CGF.EmitVariablyModifiedType(PrivTy);
5410 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005411 }
5412 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005413 IPriv = Privates.begin();
5414 auto ILHS = LHSExprs.begin();
5415 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005416 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005417 if ((*IPriv)->getType()->isArrayType()) {
5418 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005419 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5420 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005421 EmitOMPAggregateReduction(
5422 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5423 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5424 emitReductionCombiner(CGF, E);
5425 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005426 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005427 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005428 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005429 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005430 ++IPriv;
5431 ++ILHS;
5432 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005433 }
5434 Scope.ForceCleanup();
5435 CGF.FinishFunction();
5436 return Fn;
5437}
5438
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005439void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5440 const Expr *ReductionOp,
5441 const Expr *PrivateRef,
5442 const DeclRefExpr *LHS,
5443 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005444 if (PrivateRef->getType()->isArrayType()) {
5445 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005446 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5447 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005448 EmitOMPAggregateReduction(
5449 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5450 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5451 emitReductionCombiner(CGF, ReductionOp);
5452 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005453 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005454 // Emit reduction for array subscript or single variable.
5455 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005456 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005457}
5458
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005459void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005460 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005461 ArrayRef<const Expr *> LHSExprs,
5462 ArrayRef<const Expr *> RHSExprs,
5463 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005464 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005465 if (!CGF.HaveInsertPoint())
5466 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005467
5468 bool WithNowait = Options.WithNowait;
5469 bool SimpleReduction = Options.SimpleReduction;
5470
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005471 // Next code should be emitted for reduction:
5472 //
5473 // static kmp_critical_name lock = { 0 };
5474 //
5475 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5476 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5477 // ...
5478 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5479 // *(Type<n>-1*)rhs[<n>-1]);
5480 // }
5481 //
5482 // ...
5483 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5484 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5485 // RedList, reduce_func, &<lock>)) {
5486 // case 1:
5487 // ...
5488 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5489 // ...
5490 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5491 // break;
5492 // case 2:
5493 // ...
5494 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5495 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005496 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005497 // break;
5498 // default:;
5499 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005500 //
5501 // if SimpleReduction is true, only the next code is generated:
5502 // ...
5503 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5504 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005505
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005506 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005507
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005508 if (SimpleReduction) {
5509 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005510 auto IPriv = Privates.begin();
5511 auto ILHS = LHSExprs.begin();
5512 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005513 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005514 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5515 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005516 ++IPriv;
5517 ++ILHS;
5518 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005519 }
5520 return;
5521 }
5522
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005523 // 1. Build a list of reduction variables.
5524 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005525 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005526 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005527 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005528 // Reserve place for array size.
5529 ++Size;
5530 }
5531 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005532 QualType ReductionArrayTy =
5533 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5534 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005535 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005536 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005537 auto IPriv = Privates.begin();
5538 unsigned Idx = 0;
5539 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005540 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005541 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005542 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005543 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005544 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5545 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005546 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005547 // Store array size.
5548 ++Idx;
5549 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5550 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005551 llvm::Value *Size = CGF.Builder.CreateIntCast(
5552 CGF.getVLASize(
5553 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005554 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005555 CGF.SizeTy, /*isSigned=*/false);
5556 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5557 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005558 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005559 }
5560
5561 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005562 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005563 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5564 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005565
5566 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005567 std::string Name = getName({"reduction"});
5568 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005569
5570 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5571 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005572 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5573 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5574 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5575 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005576 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005577 llvm::Value *Args[] = {
5578 IdentTLoc, // ident_t *<loc>
5579 ThreadId, // i32 <gtid>
5580 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5581 ReductionArrayTySize, // size_type sizeof(RedList)
5582 RL, // void *RedList
5583 ReductionFn, // void (*) (void *, void *) <reduce_func>
5584 Lock // kmp_critical_name *&<lock>
5585 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005586 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005587 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5588 : OMPRTL__kmpc_reduce),
5589 Args);
5590
5591 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005592 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5593 llvm::SwitchInst *SwInst =
5594 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005595
5596 // 6. Build case 1:
5597 // ...
5598 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5599 // ...
5600 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5601 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005602 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005603 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5604 CGF.EmitBlock(Case1BB);
5605
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005606 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5607 llvm::Value *EndArgs[] = {
5608 IdentTLoc, // ident_t *<loc>
5609 ThreadId, // i32 <gtid>
5610 Lock // kmp_critical_name *&<lock>
5611 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005612 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5613 CodeGenFunction &CGF, PrePostActionTy &Action) {
5614 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005615 auto IPriv = Privates.begin();
5616 auto ILHS = LHSExprs.begin();
5617 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005618 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005619 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5620 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005621 ++IPriv;
5622 ++ILHS;
5623 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005624 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005625 };
5626 RegionCodeGenTy RCG(CodeGen);
5627 CommonActionTy Action(
5628 nullptr, llvm::None,
5629 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5630 : OMPRTL__kmpc_end_reduce),
5631 EndArgs);
5632 RCG.setAction(Action);
5633 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005634
5635 CGF.EmitBranch(DefaultBB);
5636
5637 // 7. Build case 2:
5638 // ...
5639 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5640 // ...
5641 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005642 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005643 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5644 CGF.EmitBlock(Case2BB);
5645
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005646 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5647 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005648 auto ILHS = LHSExprs.begin();
5649 auto IRHS = RHSExprs.begin();
5650 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005651 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005652 const Expr *XExpr = nullptr;
5653 const Expr *EExpr = nullptr;
5654 const Expr *UpExpr = nullptr;
5655 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005656 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005657 if (BO->getOpcode() == BO_Assign) {
5658 XExpr = BO->getLHS();
5659 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005660 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005661 }
5662 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005663 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005664 if (RHSExpr) {
5665 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005666 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005667 RHSExpr->IgnoreParenImpCasts())) {
5668 // If this is a conditional operator, analyze its condition for
5669 // min/max reduction operator.
5670 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005671 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005672 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005673 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5674 EExpr = BORHS->getRHS();
5675 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005676 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005677 }
5678 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005679 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005680 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005681 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5682 const Expr *EExpr, const Expr *UpExpr) {
5683 LValue X = CGF.EmitLValue(XExpr);
5684 RValue E;
5685 if (EExpr)
5686 E = CGF.EmitAnyExpr(EExpr);
5687 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005688 X, E, BO, /*IsXLHSInRHSPart=*/true,
5689 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005690 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005691 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5692 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005693 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005694 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5695 CGF.emitOMPSimpleStore(
5696 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5697 VD->getType().getNonReferenceType(), Loc);
5698 return LHSTemp;
5699 });
5700 (void)PrivateScope.Privatize();
5701 return CGF.EmitAnyExpr(UpExpr);
5702 });
5703 };
5704 if ((*IPriv)->getType()->isArrayType()) {
5705 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005706 const auto *RHSVar =
5707 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005708 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5709 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005710 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005711 // Emit atomic reduction for array subscript or single variable.
5712 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005713 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005714 } else {
5715 // Emit as a critical region.
5716 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005717 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005718 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005719 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005720 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005721 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005722 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5723 Action.Enter(CGF);
5724 emitReductionCombiner(CGF, E);
5725 },
5726 Loc);
5727 };
5728 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005729 const auto *LHSVar =
5730 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5731 const auto *RHSVar =
5732 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005733 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5734 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005735 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005736 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005737 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005738 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005739 ++ILHS;
5740 ++IRHS;
5741 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005742 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005743 };
5744 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5745 if (!WithNowait) {
5746 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5747 llvm::Value *EndArgs[] = {
5748 IdentTLoc, // ident_t *<loc>
5749 ThreadId, // i32 <gtid>
5750 Lock // kmp_critical_name *&<lock>
5751 };
5752 CommonActionTy Action(nullptr, llvm::None,
5753 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5754 EndArgs);
5755 AtomicRCG.setAction(Action);
5756 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005757 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005758 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005759 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005760
5761 CGF.EmitBranch(DefaultBB);
5762 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5763}
5764
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005765/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005766/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5767static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5768 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005769 SmallString<256> Buffer;
5770 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005771 const clang::DeclRefExpr *DE;
5772 const VarDecl *D = ::getBaseDecl(Ref, DE);
5773 if (!D)
5774 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5775 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005776 std::string Name = CGM.getOpenMPRuntime().getName(
5777 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5778 Out << Prefix << Name << "_"
5779 << D->getCanonicalDecl()->getLocStart().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005780 return Out.str();
5781}
5782
5783/// Emits reduction initializer function:
5784/// \code
5785/// void @.red_init(void* %arg) {
5786/// %0 = bitcast void* %arg to <type>*
5787/// store <type> <init>, <type>* %0
5788/// ret void
5789/// }
5790/// \endcode
5791static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5792 SourceLocation Loc,
5793 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005794 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005795 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005796 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5797 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005798 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005799 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005800 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005801 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005802 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005803 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005804 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005805 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005806 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005807 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005808 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005809 Address PrivateAddr = CGF.EmitLoadOfPointer(
5810 CGF.GetAddrOfLocalVar(&Param),
5811 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5812 llvm::Value *Size = nullptr;
5813 // If the size of the reduction item is non-constant, load it from global
5814 // threadprivate variable.
5815 if (RCG.getSizes(N).second) {
5816 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5817 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005818 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005819 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5820 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005821 }
5822 RCG.emitAggregateType(CGF, N, Size);
5823 LValue SharedLVal;
5824 // If initializer uses initializer from declare reduction construct, emit a
5825 // pointer to the address of the original reduction item (reuired by reduction
5826 // initializer)
5827 if (RCG.usesReductionInitializer(N)) {
5828 Address SharedAddr =
5829 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5830 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005831 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005832 SharedAddr = CGF.EmitLoadOfPointer(
5833 SharedAddr,
5834 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005835 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5836 } else {
5837 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5838 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5839 CGM.getContext().VoidPtrTy);
5840 }
5841 // Emit the initializer:
5842 // %0 = bitcast void* %arg to <type>*
5843 // store <type> <init>, <type>* %0
5844 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5845 [](CodeGenFunction &) { return false; });
5846 CGF.FinishFunction();
5847 return Fn;
5848}
5849
5850/// Emits reduction combiner function:
5851/// \code
5852/// void @.red_comb(void* %arg0, void* %arg1) {
5853/// %lhs = bitcast void* %arg0 to <type>*
5854/// %rhs = bitcast void* %arg1 to <type>*
5855/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5856/// store <type> %2, <type>* %lhs
5857/// ret void
5858/// }
5859/// \endcode
5860static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5861 SourceLocation Loc,
5862 ReductionCodeGen &RCG, unsigned N,
5863 const Expr *ReductionOp,
5864 const Expr *LHS, const Expr *RHS,
5865 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005866 ASTContext &C = CGM.getContext();
5867 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5868 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005869 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005870 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5871 C.VoidPtrTy, ImplicitParamDecl::Other);
5872 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5873 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005874 Args.emplace_back(&ParamInOut);
5875 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005876 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005877 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005878 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005879 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005880 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005881 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005882 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005883 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005884 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005885 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005886 llvm::Value *Size = nullptr;
5887 // If the size of the reduction item is non-constant, load it from global
5888 // threadprivate variable.
5889 if (RCG.getSizes(N).second) {
5890 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5891 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005892 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005893 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5894 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005895 }
5896 RCG.emitAggregateType(CGF, N, Size);
5897 // Remap lhs and rhs variables to the addresses of the function arguments.
5898 // %lhs = bitcast void* %arg0 to <type>*
5899 // %rhs = bitcast void* %arg1 to <type>*
5900 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005901 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005902 // Pull out the pointer to the variable.
5903 Address PtrAddr = CGF.EmitLoadOfPointer(
5904 CGF.GetAddrOfLocalVar(&ParamInOut),
5905 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5906 return CGF.Builder.CreateElementBitCast(
5907 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5908 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005909 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005910 // Pull out the pointer to the variable.
5911 Address PtrAddr = CGF.EmitLoadOfPointer(
5912 CGF.GetAddrOfLocalVar(&ParamIn),
5913 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5914 return CGF.Builder.CreateElementBitCast(
5915 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5916 });
5917 PrivateScope.Privatize();
5918 // Emit the combiner body:
5919 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5920 // store <type> %2, <type>* %lhs
5921 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5922 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5923 cast<DeclRefExpr>(RHS));
5924 CGF.FinishFunction();
5925 return Fn;
5926}
5927
5928/// Emits reduction finalizer function:
5929/// \code
5930/// void @.red_fini(void* %arg) {
5931/// %0 = bitcast void* %arg to <type>*
5932/// <destroy>(<type>* %0)
5933/// ret void
5934/// }
5935/// \endcode
5936static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5937 SourceLocation Loc,
5938 ReductionCodeGen &RCG, unsigned N) {
5939 if (!RCG.needCleanups(N))
5940 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005941 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005942 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005943 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5944 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005945 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005946 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005947 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005948 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005949 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005950 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005951 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005952 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005953 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005954 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005955 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005956 Address PrivateAddr = CGF.EmitLoadOfPointer(
5957 CGF.GetAddrOfLocalVar(&Param),
5958 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5959 llvm::Value *Size = nullptr;
5960 // If the size of the reduction item is non-constant, load it from global
5961 // threadprivate variable.
5962 if (RCG.getSizes(N).second) {
5963 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5964 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005965 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005966 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5967 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005968 }
5969 RCG.emitAggregateType(CGF, N, Size);
5970 // Emit the finalizer body:
5971 // <destroy>(<type>* %0)
5972 RCG.emitCleanups(CGF, N, PrivateAddr);
5973 CGF.FinishFunction();
5974 return Fn;
5975}
5976
5977llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5978 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5979 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5980 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5981 return nullptr;
5982
5983 // Build typedef struct:
5984 // kmp_task_red_input {
5985 // void *reduce_shar; // shared reduction item
5986 // size_t reduce_size; // size of data item
5987 // void *reduce_init; // data initialization routine
5988 // void *reduce_fini; // data finalization routine
5989 // void *reduce_comb; // data combiner routine
5990 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5991 // } kmp_task_red_input_t;
5992 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005993 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005994 RD->startDefinition();
5995 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5996 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5997 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5998 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5999 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6000 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6001 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6002 RD->completeDefinition();
6003 QualType RDType = C.getRecordType(RD);
6004 unsigned Size = Data.ReductionVars.size();
6005 llvm::APInt ArraySize(/*numBits=*/64, Size);
6006 QualType ArrayRDType = C.getConstantArrayType(
6007 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6008 // kmp_task_red_input_t .rd_input.[Size];
6009 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6010 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6011 Data.ReductionOps);
6012 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6013 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6014 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6015 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6016 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6017 TaskRedInput.getPointer(), Idxs,
6018 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6019 ".rd_input.gep.");
6020 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6021 // ElemLVal.reduce_shar = &Shareds[Cnt];
6022 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6023 RCG.emitSharedLValue(CGF, Cnt);
6024 llvm::Value *CastedShared =
6025 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6026 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6027 RCG.emitAggregateType(CGF, Cnt);
6028 llvm::Value *SizeValInChars;
6029 llvm::Value *SizeVal;
6030 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6031 // We use delayed creation/initialization for VLAs, array sections and
6032 // custom reduction initializations. It is required because runtime does not
6033 // provide the way to pass the sizes of VLAs/array sections to
6034 // initializer/combiner/finalizer functions and does not pass the pointer to
6035 // original reduction item to the initializer. Instead threadprivate global
6036 // variables are used to store these values and use them in the functions.
6037 bool DelayedCreation = !!SizeVal;
6038 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6039 /*isSigned=*/false);
6040 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6041 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6042 // ElemLVal.reduce_init = init;
6043 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6044 llvm::Value *InitAddr =
6045 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6046 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6047 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6048 // ElemLVal.reduce_fini = fini;
6049 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6050 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6051 llvm::Value *FiniAddr = Fini
6052 ? CGF.EmitCastToVoidPtr(Fini)
6053 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6054 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6055 // ElemLVal.reduce_comb = comb;
6056 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6057 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6058 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6059 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6060 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6061 // ElemLVal.flags = 0;
6062 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6063 if (DelayedCreation) {
6064 CGF.EmitStoreOfScalar(
6065 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6066 FlagsLVal);
6067 } else
6068 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6069 }
6070 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6071 // *data);
6072 llvm::Value *Args[] = {
6073 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6074 /*isSigned=*/true),
6075 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6076 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6077 CGM.VoidPtrTy)};
6078 return CGF.EmitRuntimeCall(
6079 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6080}
6081
6082void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6083 SourceLocation Loc,
6084 ReductionCodeGen &RCG,
6085 unsigned N) {
6086 auto Sizes = RCG.getSizes(N);
6087 // Emit threadprivate global variable if the type is non-constant
6088 // (Sizes.second = nullptr).
6089 if (Sizes.second) {
6090 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6091 /*isSigned=*/false);
6092 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6093 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006094 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006095 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6096 }
6097 // Store address of the original reduction item if custom initializer is used.
6098 if (RCG.usesReductionInitializer(N)) {
6099 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6100 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006101 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006102 CGF.Builder.CreateStore(
6103 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6104 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6105 SharedAddr, /*IsVolatile=*/false);
6106 }
6107}
6108
6109Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6110 SourceLocation Loc,
6111 llvm::Value *ReductionsPtr,
6112 LValue SharedLVal) {
6113 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6114 // *d);
6115 llvm::Value *Args[] = {
6116 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6117 /*isSigned=*/true),
6118 ReductionsPtr,
6119 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6120 CGM.VoidPtrTy)};
6121 return Address(
6122 CGF.EmitRuntimeCall(
6123 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6124 SharedLVal.getAlignment());
6125}
6126
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006127void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6128 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006129 if (!CGF.HaveInsertPoint())
6130 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006131 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6132 // global_tid);
6133 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6134 // Ignore return result until untied tasks are supported.
6135 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006136 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6137 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006138}
6139
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006140void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006141 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006142 const RegionCodeGenTy &CodeGen,
6143 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006144 if (!CGF.HaveInsertPoint())
6145 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006146 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006147 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006148}
6149
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006150namespace {
6151enum RTCancelKind {
6152 CancelNoreq = 0,
6153 CancelParallel = 1,
6154 CancelLoop = 2,
6155 CancelSections = 3,
6156 CancelTaskgroup = 4
6157};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006158} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006159
6160static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6161 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006162 if (CancelRegion == OMPD_parallel)
6163 CancelKind = CancelParallel;
6164 else if (CancelRegion == OMPD_for)
6165 CancelKind = CancelLoop;
6166 else if (CancelRegion == OMPD_sections)
6167 CancelKind = CancelSections;
6168 else {
6169 assert(CancelRegion == OMPD_taskgroup);
6170 CancelKind = CancelTaskgroup;
6171 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006172 return CancelKind;
6173}
6174
6175void CGOpenMPRuntime::emitCancellationPointCall(
6176 CodeGenFunction &CGF, SourceLocation Loc,
6177 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006178 if (!CGF.HaveInsertPoint())
6179 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006180 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6181 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006182 if (auto *OMPRegionInfo =
6183 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006184 // For 'cancellation point taskgroup', the task region info may not have a
6185 // cancel. This may instead happen in another adjacent task.
6186 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006187 llvm::Value *Args[] = {
6188 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6189 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006190 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006191 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006192 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6193 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006194 // exit from construct;
6195 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006196 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6197 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6198 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006199 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6200 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006201 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006202 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006203 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006204 CGF.EmitBranchThroughCleanup(CancelDest);
6205 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6206 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006207 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006208}
6209
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006210void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006211 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006212 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006213 if (!CGF.HaveInsertPoint())
6214 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006215 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6216 // kmp_int32 cncl_kind);
6217 if (auto *OMPRegionInfo =
6218 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006219 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6220 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006221 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006222 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006223 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006224 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6225 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006226 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006227 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006228 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006229 // exit from construct;
6230 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006231 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6232 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6233 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006234 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6235 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006236 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006237 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006238 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6239 CGF.EmitBranchThroughCleanup(CancelDest);
6240 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6241 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006242 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006243 emitOMPIfClause(CGF, IfCond, ThenGen,
6244 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006245 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006246 RegionCodeGenTy ThenRCG(ThenGen);
6247 ThenRCG(CGF);
6248 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006249 }
6250}
Samuel Antaobed3c462015-10-02 16:14:20 +00006251
Samuel Antaoee8fb302016-01-06 13:42:12 +00006252void CGOpenMPRuntime::emitTargetOutlinedFunction(
6253 const OMPExecutableDirective &D, StringRef ParentName,
6254 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006255 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006256 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006257 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6258 IsOffloadEntry, CodeGen);
6259}
6260
6261void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6262 const OMPExecutableDirective &D, StringRef ParentName,
6263 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6264 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006265 // Create a unique name for the entry function using the source location
6266 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006267 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006268 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006269 //
6270 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006271 // mangled name of the function that encloses the target region and BB is the
6272 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006273
6274 unsigned DeviceID;
6275 unsigned FileID;
6276 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006277 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006278 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006279 SmallString<64> EntryFnName;
6280 {
6281 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006282 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6283 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006284 }
6285
Alexey Bataev475a7442018-01-12 19:39:11 +00006286 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006287
Samuel Antaobed3c462015-10-02 16:14:20 +00006288 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006289 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006290 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006291
Samuel Antao6d004262016-06-16 18:39:34 +00006292 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006293
6294 // If this target outline function is not an offload entry, we don't need to
6295 // register it.
6296 if (!IsOffloadEntry)
6297 return;
6298
6299 // The target region ID is used by the runtime library to identify the current
6300 // target region, so it only has to be unique and not necessarily point to
6301 // anything. It could be the pointer to the outlined function that implements
6302 // the target region, but we aren't using that so that the compiler doesn't
6303 // need to keep that, and could therefore inline the host function if proven
6304 // worthwhile during optimization. In the other hand, if emitting code for the
6305 // device, the ID has to be the function address so that it can retrieved from
6306 // the offloading entry and launched by the runtime library. We also mark the
6307 // outlined function to have external linkage in case we are emitting code for
6308 // the device, because these functions will be entry points to the device.
6309
6310 if (CGM.getLangOpts().OpenMPIsDevice) {
6311 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006312 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006313 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006314 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006315 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006316 OutlinedFnID = new llvm::GlobalVariable(
6317 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006318 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006319 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006320 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006321
6322 // Register the information for the entry associated with this target region.
6323 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006324 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006325 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006326}
6327
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006328/// discard all CompoundStmts intervening between two constructs
6329static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006330 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006331 Body = CS->body_front();
6332
6333 return Body;
6334}
6335
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006336/// Emit the number of teams for a target directive. Inspect the num_teams
6337/// clause associated with a teams construct combined or closely nested
6338/// with the target directive.
6339///
6340/// Emit a team of size one for directives such as 'target parallel' that
6341/// have no associated teams construct.
6342///
6343/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006344static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006345emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6346 CodeGenFunction &CGF,
6347 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006348 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6349 "teams directive expected to be "
6350 "emitted only for the host!");
6351
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006352 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006353
6354 // If the target directive is combined with a teams directive:
6355 // Return the value in the num_teams clause, if any.
6356 // Otherwise, return 0 to denote the runtime default.
6357 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6358 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6359 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006360 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6361 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006362 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6363 /*IsSigned=*/true);
6364 }
6365
6366 // The default value is 0.
6367 return Bld.getInt32(0);
6368 }
6369
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006370 // If the target directive is combined with a parallel directive but not a
6371 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006372 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6373 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006374
6375 // If the current target region has a teams region enclosed, we need to get
6376 // the number of teams to pass to the runtime function call. This is done
6377 // by generating the expression in a inlined region. This is required because
6378 // the expression is captured in the enclosing target environment when the
6379 // teams directive is not combined with target.
6380
Alexey Bataev475a7442018-01-12 19:39:11 +00006381 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006382
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006383 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006384 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006385 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006386 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006387 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6388 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6389 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6390 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6391 /*IsSigned=*/true);
6392 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006393
Alexey Bataev50a1c782017-12-01 21:31:08 +00006394 // If we have an enclosed teams directive but no num_teams clause we use
6395 // the default value 0.
6396 return Bld.getInt32(0);
6397 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006398 }
6399
6400 // No teams associated with the directive.
6401 return nullptr;
6402}
6403
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006404/// Emit the number of threads for a target directive. Inspect the
6405/// thread_limit clause associated with a teams construct combined or closely
6406/// nested with the target directive.
6407///
6408/// Emit the num_threads clause for directives such as 'target parallel' that
6409/// have no associated teams construct.
6410///
6411/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006412static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006413emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6414 CodeGenFunction &CGF,
6415 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006416 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6417 "teams directive expected to be "
6418 "emitted only for the host!");
6419
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006420 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006421
6422 //
6423 // If the target directive is combined with a teams directive:
6424 // Return the value in the thread_limit clause, if any.
6425 //
6426 // If the target directive is combined with a parallel directive:
6427 // Return the value in the num_threads clause, if any.
6428 //
6429 // If both clauses are set, select the minimum of the two.
6430 //
6431 // If neither teams or parallel combined directives set the number of threads
6432 // in a team, return 0 to denote the runtime default.
6433 //
6434 // If this is not a teams directive return nullptr.
6435
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006436 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6437 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006438 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6439 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006440 llvm::Value *ThreadLimitVal = nullptr;
6441
6442 if (const auto *ThreadLimitClause =
6443 D.getSingleClause<OMPThreadLimitClause>()) {
6444 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006445 llvm::Value *ThreadLimit =
6446 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6447 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006448 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6449 /*IsSigned=*/true);
6450 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006451
6452 if (const auto *NumThreadsClause =
6453 D.getSingleClause<OMPNumThreadsClause>()) {
6454 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6455 llvm::Value *NumThreads =
6456 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6457 /*IgnoreResultAssign*/ true);
6458 NumThreadsVal =
6459 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6460 }
6461
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006462 // Select the lesser of thread_limit and num_threads.
6463 if (NumThreadsVal)
6464 ThreadLimitVal = ThreadLimitVal
6465 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6466 ThreadLimitVal),
6467 NumThreadsVal, ThreadLimitVal)
6468 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006469
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006470 // Set default value passed to the runtime if either teams or a target
6471 // parallel type directive is found but no clause is specified.
6472 if (!ThreadLimitVal)
6473 ThreadLimitVal = DefaultThreadLimitVal;
6474
6475 return ThreadLimitVal;
6476 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006477
Samuel Antaob68e2db2016-03-03 16:20:23 +00006478 // If the current target region has a teams region enclosed, we need to get
6479 // the thread limit to pass to the runtime function call. This is done
6480 // by generating the expression in a inlined region. This is required because
6481 // the expression is captured in the enclosing target environment when the
6482 // teams directive is not combined with target.
6483
Alexey Bataev475a7442018-01-12 19:39:11 +00006484 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006485
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006486 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006487 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006488 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006489 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006490 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6491 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6492 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6493 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6494 /*IsSigned=*/true);
6495 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006496
Alexey Bataev50a1c782017-12-01 21:31:08 +00006497 // If we have an enclosed teams directive but no thread_limit clause we
6498 // use the default value 0.
6499 return CGF.Builder.getInt32(0);
6500 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006501 }
6502
6503 // No teams associated with the directive.
6504 return nullptr;
6505}
6506
Samuel Antao86ace552016-04-27 22:40:57 +00006507namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006508LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6509
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006510// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006511// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6512// It provides a convenient interface to obtain the information and generate
6513// code for that information.
6514class MappableExprsHandler {
6515public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006516 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006517 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006518 enum OpenMPOffloadMappingFlags : uint64_t {
6519 /// No flags
6520 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006521 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006522 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006523 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006524 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006525 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006526 /// if it was already mapped before.
6527 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006528 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006529 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006530 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006531 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006532 /// pointer and the pointee should be mapped.
6533 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006534 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006535 /// passed to the target kernel as an argument.
6536 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006537 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006538 /// in the current position for the data being mapped. Used when we have the
6539 /// use_device_ptr clause.
6540 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006541 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006542 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006543 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006544 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006545 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006546 /// Implicit map
6547 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006548 /// The 16 MSBs of the flags indicate whether the entry is member of some
6549 /// struct/class.
6550 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6551 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006552 };
6553
Samuel Antaocc10b852016-07-28 14:23:26 +00006554 /// Class that associates information with a base pointer to be passed to the
6555 /// runtime library.
6556 class BasePointerInfo {
6557 /// The base pointer.
6558 llvm::Value *Ptr = nullptr;
6559 /// The base declaration that refers to this device pointer, or null if
6560 /// there is none.
6561 const ValueDecl *DevPtrDecl = nullptr;
6562
6563 public:
6564 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6565 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6566 llvm::Value *operator*() const { return Ptr; }
6567 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6568 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6569 };
6570
Alexey Bataevb3638132018-07-19 16:34:13 +00006571 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6572 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6573 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6574
6575 /// Map between a struct and the its lowest & highest elements which have been
6576 /// mapped.
6577 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6578 /// HE(FieldIndex, Pointer)}
6579 struct StructRangeInfoTy {
6580 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6581 0, Address::invalid()};
6582 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6583 0, Address::invalid()};
6584 Address Base = Address::invalid();
6585 };
Samuel Antao86ace552016-04-27 22:40:57 +00006586
6587private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006588 /// Kind that defines how a device pointer has to be returned.
6589 struct MapInfo {
6590 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6591 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6592 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6593 bool ReturnDevicePointer = false;
6594 bool IsImplicit = false;
6595
6596 MapInfo() = default;
6597 MapInfo(
6598 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6599 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6600 bool ReturnDevicePointer, bool IsImplicit)
6601 : Components(Components), MapType(MapType),
6602 MapTypeModifier(MapTypeModifier),
6603 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6604 };
6605
6606 /// If use_device_ptr is used on a pointer which is a struct member and there
6607 /// is no map information about it, then emission of that entry is deferred
6608 /// until the whole struct has been processed.
6609 struct DeferredDevicePtrEntryTy {
6610 const Expr *IE = nullptr;
6611 const ValueDecl *VD = nullptr;
6612
6613 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6614 : IE(IE), VD(VD) {}
6615 };
6616
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006617 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006618 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006619
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006620 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006621 CodeGenFunction &CGF;
6622
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006623 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006624 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6625
Samuel Antao6890b092016-07-28 14:25:09 +00006626 /// Map between device pointer declarations and their expression components.
6627 /// The key value for declarations in 'this' is null.
6628 llvm::DenseMap<
6629 const ValueDecl *,
6630 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6631 DevPointersMap;
6632
Samuel Antao86ace552016-04-27 22:40:57 +00006633 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006634 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006635
6636 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006637 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006638 ExprTy = RefTy->getPointeeType().getCanonicalType();
6639
6640 // Given that an array section is considered a built-in type, we need to
6641 // do the calculation based on the length of the section instead of relying
6642 // on CGF.getTypeSize(E->getType()).
6643 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6644 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6645 OAE->getBase()->IgnoreParenImpCasts())
6646 .getCanonicalType();
6647
6648 // If there is no length associated with the expression, that means we
6649 // are using the whole length of the base.
6650 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6651 return CGF.getTypeSize(BaseTy);
6652
6653 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006654 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006655 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006656 } else {
6657 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006658 assert(ATy && "Expecting array type if not a pointer type.");
6659 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6660 }
6661
6662 // If we don't have a length at this point, that is because we have an
6663 // array section with a single element.
6664 if (!OAE->getLength())
6665 return ElemSize;
6666
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006667 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006668 LengthVal =
6669 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6670 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6671 }
6672 return CGF.getTypeSize(ExprTy);
6673 }
6674
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006675 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006676 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006677 /// map as the first one of a series of maps that relate to the same map
6678 /// expression.
Alexey Bataevb3638132018-07-19 16:34:13 +00006679 OpenMPOffloadMappingFlags getMapTypeBits(OpenMPMapClauseKind MapType,
6680 OpenMPMapClauseKind MapTypeModifier,
6681 bool IsImplicit, bool AddPtrFlag,
6682 bool AddIsTargetParamFlag) const {
6683 OpenMPOffloadMappingFlags Bits =
6684 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006685 switch (MapType) {
6686 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006687 case OMPC_MAP_release:
6688 // alloc and release is the default behavior in the runtime library, i.e.
6689 // if we don't pass any bits alloc/release that is what the runtime is
6690 // going to do. Therefore, we don't need to signal anything for these two
6691 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006692 break;
6693 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006694 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006695 break;
6696 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006697 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006698 break;
6699 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006700 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006701 break;
6702 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006703 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006704 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006705 case OMPC_MAP_always:
6706 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006707 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006708 }
6709 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006710 Bits |= OMP_MAP_PTR_AND_OBJ;
6711 if (AddIsTargetParamFlag)
6712 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006713 if (MapTypeModifier == OMPC_MAP_always)
6714 Bits |= OMP_MAP_ALWAYS;
6715 return Bits;
6716 }
6717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006718 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006719 /// final array section, is one whose length can't be proved to be one.
6720 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006721 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006722
6723 // It is not an array section and therefore not a unity-size one.
6724 if (!OASE)
6725 return false;
6726
6727 // An array section with no colon always refer to a single element.
6728 if (OASE->getColonLoc().isInvalid())
6729 return false;
6730
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006731 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006732
6733 // If we don't have a length we have to check if the array has size 1
6734 // for this dimension. Also, we should always expect a length if the
6735 // base type is pointer.
6736 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006737 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6738 OASE->getBase()->IgnoreParenImpCasts())
6739 .getCanonicalType();
6740 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006741 return ATy->getSize().getSExtValue() != 1;
6742 // If we don't have a constant dimension length, we have to consider
6743 // the current section as having any size, so it is not necessarily
6744 // unitary. If it happen to be unity size, that's user fault.
6745 return true;
6746 }
6747
6748 // Check if the length evaluates to 1.
6749 llvm::APSInt ConstLength;
6750 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6751 return true; // Can have more that size 1.
6752
6753 return ConstLength.getSExtValue() != 1;
6754 }
6755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006756 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006757 /// bits for the provided map type, map modifier, and expression components.
6758 /// \a IsFirstComponent should be set to true if the provided set of
6759 /// components is the first associated with a capture.
6760 void generateInfoForComponentList(
6761 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6762 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006763 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006764 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006765 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
6766 bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006767 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006768 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006769 // base pointer, section pointer, size, flags
6770 // (to add to the ones that come from the map type and modifier).
6771 //
6772 // double d;
6773 // int i[100];
6774 // float *p;
6775 //
6776 // struct S1 {
6777 // int i;
6778 // float f[50];
6779 // }
6780 // struct S2 {
6781 // int i;
6782 // float f[50];
6783 // S1 s;
6784 // double *p;
6785 // struct S2 *ps;
6786 // }
6787 // S2 s;
6788 // S2 *ps;
6789 //
6790 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006791 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006792 //
6793 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006794 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006795 //
6796 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006797 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006798 //
6799 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006800 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006801 //
6802 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006803 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006804 //
6805 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006806 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006807 //
6808 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006809 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006810 //
6811 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006812 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006813 //
6814 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006815 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006816 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006817 // map(to: s.p[:22])
6818 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6819 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6820 // &(s.p), &(s.p[0]), 22*sizeof(double),
6821 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6822 // (*) alloc space for struct members, only this is a target parameter
6823 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6824 // optimizes this entry out, same in the examples below)
6825 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006826 //
6827 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006828 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006829 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006830 // map(from: s.ps->s.i)
6831 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6832 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6833 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006834 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006835 // map(to: s.ps->ps)
6836 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6837 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6838 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006839 //
6840 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006841 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6842 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6843 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6844 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006845 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006846 // map(to: s.ps->ps->s.f[:22])
6847 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6848 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6849 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6850 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006851 //
6852 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006853 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006854 //
6855 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006856 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006857 //
6858 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006859 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006860 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006861 // map(from: ps->p)
6862 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006863 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006864 // map(to: ps->p[:22])
6865 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6866 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6867 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006868 //
6869 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006870 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006871 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006872 // map(from: ps->ps->s.i)
6873 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6874 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6875 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006876 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006877 // map(from: ps->ps->ps)
6878 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6879 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6880 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006881 //
6882 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006883 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6884 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6885 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6886 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006887 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006888 // map(to: ps->ps->ps->s.f[:22])
6889 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6890 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6891 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6892 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6893 //
6894 // map(to: s.f[:22]) map(from: s.p[:33])
6895 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6896 // sizeof(double*) (**), TARGET_PARAM
6897 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
6898 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
6899 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
6900 // (*) allocate contiguous space needed to fit all mapped members even if
6901 // we allocate space for members not mapped (in this example,
6902 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
6903 // them as well because they fall between &s.f[0] and &s.p)
6904 //
6905 // map(from: s.f[:22]) map(to: ps->p[:33])
6906 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
6907 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6908 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
6909 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
6910 // (*) the struct this entry pertains to is the 2nd element in the list of
6911 // arguments, hence MEMBER_OF(2)
6912 //
6913 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
6914 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
6915 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
6916 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
6917 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6918 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
6919 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
6920 // (*) the struct this entry pertains to is the 4th element in the list
6921 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00006922
6923 // Track if the map information being generated is the first for a capture.
6924 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006925 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006926
6927 // Scan the components from the base to the complete expression.
6928 auto CI = Components.rbegin();
6929 auto CE = Components.rend();
6930 auto I = CI;
6931
6932 // Track if the map information being generated is the first for a list of
6933 // components.
6934 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006935 Address BP = Address::invalid();
Samuel Antao86ace552016-04-27 22:40:57 +00006936
Erich Keanee69755a2018-07-19 17:19:16 +00006937 if (isa<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006938 // The base is the 'this' pointer. The content of the pointer is going
6939 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00006940 BP = CGF.LoadCXXThisAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00006941 } else {
6942 // The base is the reference to the variable.
6943 // BP = &Var.
Alexey Bataevb3638132018-07-19 16:34:13 +00006944 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00006945 if (const auto *VD =
6946 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6947 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataevb3638132018-07-19 16:34:13 +00006948 isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006949 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
6950 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006951 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006952 }
Alexey Bataev92327c52018-03-26 16:40:55 +00006953 }
Samuel Antao86ace552016-04-27 22:40:57 +00006954
6955 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006956 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006957 // reference. References are ignored for mapping purposes.
6958 QualType Ty =
6959 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6960 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00006961 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00006962
6963 // We do not need to generate individual map information for the
6964 // pointer, it can be associated with the combined storage.
6965 ++I;
6966 }
6967 }
6968
Alexey Bataevb3638132018-07-19 16:34:13 +00006969 // Track whether a component of the list should be marked as MEMBER_OF some
6970 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
6971 // in a component list should be marked as MEMBER_OF, all subsequent entries
6972 // do not belong to the base struct. E.g.
6973 // struct S2 s;
6974 // s.ps->ps->ps->f[:]
6975 // (1) (2) (3) (4)
6976 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
6977 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
6978 // is the pointee of ps(2) which is not member of struct s, so it should not
6979 // be marked as such (it is still PTR_AND_OBJ).
6980 // The variable is initialized to false so that PTR_AND_OBJ entries which
6981 // are not struct members are not considered (e.g. array of pointers to
6982 // data).
6983 bool ShouldBeMemberOf = false;
6984
6985 // Variable keeping track of whether or not we have encountered a component
6986 // in the component list which is a member expression. Useful when we have a
6987 // pointer or a final array section, in which case it is the previous
6988 // component in the list which tells us whether we have a member expression.
6989 // E.g. X.f[:]
6990 // While processing the final array section "[:]" it is "f" which tells us
6991 // whether we are dealing with a member of a declared struct.
6992 const MemberExpr *EncounteredME = nullptr;
6993
Samuel Antao86ace552016-04-27 22:40:57 +00006994 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00006995 // If the current component is member of a struct (parent struct) mark it.
6996 if (!EncounteredME) {
6997 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
6998 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
6999 // as MEMBER_OF the parent struct.
7000 if (EncounteredME)
7001 ShouldBeMemberOf = true;
7002 }
7003
Samuel Antao86ace552016-04-27 22:40:57 +00007004 auto Next = std::next(I);
7005
7006 // We need to generate the addresses and sizes if this is the last
7007 // component, if the component is a pointer or if it is an array section
7008 // whose length can't be proved to be one. If this is a pointer, it
7009 // becomes the base address for the following components.
7010
7011 // A final array section, is one whose length can't be proved to be one.
7012 bool IsFinalArraySection =
7013 isFinalArraySectionExpression(I->getAssociatedExpression());
7014
7015 // Get information on whether the element is a pointer. Have to do a
7016 // special treatment for array sections given that they are built-in
7017 // types.
7018 const auto *OASE =
7019 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7020 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007021 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7022 .getCanonicalType()
7023 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007024 I->getAssociatedExpression()->getType()->isAnyPointerType();
7025
7026 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007027 // If this is not the last component, we expect the pointer to be
7028 // associated with an array expression or member expression.
7029 assert((Next == CE ||
7030 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7031 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7032 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7033 "Unexpected expression");
7034
Alexey Bataevb3638132018-07-19 16:34:13 +00007035 Address LB =
7036 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007037 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Samuel Antao86ace552016-04-27 22:40:57 +00007038
Alexey Bataevb3638132018-07-19 16:34:13 +00007039 // If this component is a pointer inside the base struct then we don't
7040 // need to create any entry for it - it will be combined with the object
7041 // it is pointing to into a single PTR_AND_OBJ entry.
7042 bool IsMemberPointer =
7043 IsPointer && EncounteredME &&
7044 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7045 EncounteredME);
7046 if (!IsMemberPointer) {
7047 BasePointers.push_back(BP.getPointer());
7048 Pointers.push_back(LB.getPointer());
7049 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007050
Alexey Bataevb3638132018-07-19 16:34:13 +00007051 // We need to add a pointer flag for each map that comes from the
7052 // same expression except for the first one. We also need to signal
7053 // this map is the first one that relates with the current capture
7054 // (there is a set of entries for each capture).
7055 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
7056 MapType, MapTypeModifier, IsImplicit,
7057 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7058
7059 if (!IsExpressionFirstInfo) {
7060 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7061 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7062 if (IsPointer)
7063 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7064 OMP_MAP_DELETE);
7065
7066 if (ShouldBeMemberOf) {
7067 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7068 // should be later updated with the correct value of MEMBER_OF.
7069 Flags |= OMP_MAP_MEMBER_OF;
7070 // From now on, all subsequent PTR_AND_OBJ entries should not be
7071 // marked as MEMBER_OF.
7072 ShouldBeMemberOf = false;
7073 }
7074 }
7075
7076 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007077 }
7078
Alexey Bataevb3638132018-07-19 16:34:13 +00007079 // If we have encountered a member expression so far, keep track of the
7080 // mapped member. If the parent is "*this", then the value declaration
7081 // is nullptr.
7082 if (EncounteredME) {
7083 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7084 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007085
Alexey Bataevb3638132018-07-19 16:34:13 +00007086 // Update info about the lowest and highest elements for this struct
7087 if (!PartialStruct.Base.isValid()) {
7088 PartialStruct.LowestElem = {FieldIndex, LB};
7089 PartialStruct.HighestElem = {FieldIndex, LB};
7090 PartialStruct.Base = BP;
7091 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7092 PartialStruct.LowestElem = {FieldIndex, LB};
7093 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7094 PartialStruct.HighestElem = {FieldIndex, LB};
7095 }
7096 }
Samuel Antao86ace552016-04-27 22:40:57 +00007097
7098 // If we have a final array section, we are done with this expression.
7099 if (IsFinalArraySection)
7100 break;
7101
7102 // The pointer becomes the base for the next element.
7103 if (Next != CE)
7104 BP = LB;
7105
7106 IsExpressionFirstInfo = false;
7107 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007108 }
7109 }
7110 }
7111
Alexey Bataevb3638132018-07-19 16:34:13 +00007112 /// Return the adjusted map modifiers if the declaration a capture refers to
7113 /// appears in a first-private clause. This is expected to be used only with
7114 /// directives that start with 'target'.
7115 MappableExprsHandler::OpenMPOffloadMappingFlags
7116 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7117 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7118
7119 // A first private variable captured by reference will use only the
7120 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7121 // declaration is known as first-private in this handler.
7122 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7123 return MappableExprsHandler::OMP_MAP_PRIVATE |
7124 MappableExprsHandler::OMP_MAP_TO;
7125 return MappableExprsHandler::OMP_MAP_TO |
7126 MappableExprsHandler::OMP_MAP_FROM;
7127 }
7128
7129 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7130 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7131 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7132 << 48);
7133 }
7134
7135 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7136 OpenMPOffloadMappingFlags MemberOfFlag) {
7137 // If the entry is PTR_AND_OBJ but has not been marked with the special
7138 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7139 // marked as MEMBER_OF.
7140 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7141 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7142 return;
7143
7144 // Reset the placeholder value to prepare the flag for the assignment of the
7145 // proper MEMBER_OF value.
7146 Flags &= ~OMP_MAP_MEMBER_OF;
7147 Flags |= MemberOfFlag;
7148 }
7149
7150public:
7151 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7152 : CurDir(Dir), CGF(CGF) {
7153 // Extract firstprivate clause information.
7154 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7155 for (const auto *D : C->varlists())
7156 FirstPrivateDecls.insert(
7157 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7158 // Extract device pointer clause information.
7159 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7160 for (auto L : C->component_lists())
7161 DevPointersMap[L.first].push_back(L.second);
7162 }
7163
7164 /// Generate code for the combined entry if we have a partially mapped struct
7165 /// and take care of the mapping flags of the arguments corresponding to
7166 /// individual struct members.
7167 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7168 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7169 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7170 const StructRangeInfoTy &PartialStruct) const {
7171 // Base is the base of the struct
7172 BasePointers.push_back(PartialStruct.Base.getPointer());
7173 // Pointer is the address of the lowest element
7174 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7175 Pointers.push_back(LB);
7176 // Size is (addr of {highest+1} element) - (addr of lowest element)
7177 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7178 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7179 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7180 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7181 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7182 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7183 /*isSinged=*/false);
7184 Sizes.push_back(Size);
7185 // Map type is always TARGET_PARAM
7186 Types.push_back(OMP_MAP_TARGET_PARAM);
7187 // Remove TARGET_PARAM flag from the first element
7188 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7189
7190 // All other current entries will be MEMBER_OF the combined entry
7191 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7192 // 0xFFFF in the MEMBER_OF field).
7193 OpenMPOffloadMappingFlags MemberOfFlag =
7194 getMemberOfFlag(BasePointers.size() - 1);
7195 for (auto &M : CurTypes)
7196 setCorrectMemberOfFlag(M, MemberOfFlag);
7197 }
7198
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007199 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007200 /// types for the extracted mappable expressions. Also, for each item that
7201 /// relates with a device pointer, a pair of the relevant declaration and
7202 /// index where it occurs is appended to the device pointers info array.
7203 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007204 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7205 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007206 // We have to process the component lists that relate with the same
7207 // declaration in a single chunk so that we can generate the map flags
7208 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007209 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007210
7211 // Helper function to fill the information map for the different supported
7212 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007213 auto &&InfoGen = [&Info](
7214 const ValueDecl *D,
7215 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7216 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevb3638132018-07-19 16:34:13 +00007217 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007218 const ValueDecl *VD =
7219 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007220 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7221 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007222 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007223
Paul Robinson78fb1322016-08-01 22:12:46 +00007224 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007225 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7226 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007227 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007228 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007229 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007230 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7231 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007232 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007233 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007234 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007235 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7236 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007237 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007238 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007239 }
Samuel Antao86ace552016-04-27 22:40:57 +00007240
Samuel Antaocc10b852016-07-28 14:23:26 +00007241 // Look at the use_device_ptr clause information and mark the existing map
7242 // entries as such. If there is no map information for an entry in the
7243 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007244 // section. It is the user fault if that was not mapped before. If there is
7245 // no map information and the pointer is a struct member, then we defer the
7246 // emission of that entry until the whole struct has been processed.
7247 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7248 DeferredInfo;
7249
Paul Robinson78fb1322016-08-01 22:12:46 +00007250 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007251 for (const auto *C :
7252 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007253 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007254 assert(!L.second.empty() && "Not expecting empty list of components!");
7255 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7256 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007257 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007258 // If the first component is a member expression, we have to look into
7259 // 'this', which maps to null in the map of map information. Otherwise
7260 // look directly for the information.
7261 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7262
7263 // We potentially have map information for this declaration already.
7264 // Look for the first set of components that refer to it.
7265 if (It != Info.end()) {
7266 auto CI = std::find_if(
7267 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7268 return MI.Components.back().getAssociatedDeclaration() == VD;
7269 });
7270 // If we found a map entry, signal that the pointer has to be returned
7271 // and move on to the next declaration.
7272 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007273 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007274 continue;
7275 }
7276 }
7277
7278 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007279 // size array section - if the pointer is a struct member we defer this
7280 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007281 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007282 if (isa<MemberExpr>(IE)) {
7283 // Insert the pointer into Info to be processed by
7284 // generateInfoForComponentList. Because it is a member pointer
7285 // without a pointee, no entry will be generated for it, therefore
7286 // we need to generate one after the whole struct has been processed.
7287 // Nonetheless, generateInfoForComponentList must be called to take
7288 // the pointer into account for the calculation of the range of the
7289 // partial struct.
7290 InfoGen(nullptr, L.second, OMPC_MAP_unknown, OMPC_MAP_unknown,
7291 /*ReturnDevicePointer=*/false, C->isImplicit());
7292 DeferredInfo[nullptr].emplace_back(IE, VD);
7293 } else {
7294 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7295 this->CGF.EmitLValue(IE), IE->getExprLoc());
7296 BasePointers.emplace_back(Ptr, VD);
7297 Pointers.push_back(Ptr);
7298 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7299 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7300 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007301 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007302 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007303
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007304 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007305 // We need to know when we generate information for the first component
7306 // associated with a capture, because the mapping flags depend on it.
7307 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007308
7309 // Temporary versions of arrays
7310 MapBaseValuesArrayTy CurBasePointers;
7311 MapValuesArrayTy CurPointers;
7312 MapValuesArrayTy CurSizes;
7313 MapFlagsArrayTy CurTypes;
7314 StructRangeInfoTy PartialStruct;
7315
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007316 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007317 assert(!L.Components.empty() &&
7318 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007319
7320 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007321 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007322 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007323 this->generateInfoForComponentList(
Alexey Bataevb3638132018-07-19 16:34:13 +00007324 L.MapType, L.MapTypeModifier, L.Components, CurBasePointers,
7325 CurPointers, CurSizes, CurTypes, PartialStruct,
7326 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007327
7328 // If this entry relates with a device pointer, set the relevant
7329 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007330 if (L.ReturnDevicePointer) {
7331 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007332 "Unexpected number of mapped base pointers.");
7333
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007334 const ValueDecl *RelevantVD =
7335 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007336 assert(RelevantVD &&
7337 "No relevant declaration related with device pointer??");
7338
Alexey Bataevb3638132018-07-19 16:34:13 +00007339 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7340 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007341 }
Samuel Antao86ace552016-04-27 22:40:57 +00007342 IsFirstComponentList = false;
7343 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007344
7345 // Append any pending zero-length pointers which are struct members and
7346 // used with use_device_ptr.
7347 auto CI = DeferredInfo.find(M.first);
7348 if (CI != DeferredInfo.end()) {
7349 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7350 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7351 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7352 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7353 CurBasePointers.emplace_back(BasePtr, L.VD);
7354 CurPointers.push_back(Ptr);
7355 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7356 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7357 // value MEMBER_OF=FFFF so that the entry is later updated with the
7358 // correct value of MEMBER_OF.
7359 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7360 OMP_MAP_MEMBER_OF);
7361 }
7362 }
7363
7364 // If there is an entry in PartialStruct it means we have a struct with
7365 // individual members mapped. Emit an extra combined entry.
7366 if (PartialStruct.Base.isValid())
7367 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7368 PartialStruct);
7369
7370 // We need to append the results of this capture to what we already have.
7371 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7372 Pointers.append(CurPointers.begin(), CurPointers.end());
7373 Sizes.append(CurSizes.begin(), CurSizes.end());
7374 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007375 }
7376 }
7377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007378 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007379 /// associated to a given capture.
7380 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007381 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007382 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007383 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007384 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7385 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007386 assert(!Cap->capturesVariableArrayType() &&
7387 "Not expecting to generate map info for a variable array type!");
7388
Samuel Antao6890b092016-07-28 14:25:09 +00007389 // We need to know when we generating information for the first component
7390 // associated with a capture, because the mapping flags depend on it.
7391 bool IsFirstComponentList = true;
7392
Alexey Bataevb3638132018-07-19 16:34:13 +00007393 const ValueDecl *VD = Cap->capturesThis()
7394 ? nullptr
7395 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007396
Samuel Antao6890b092016-07-28 14:25:09 +00007397 // If this declaration appears in a is_device_ptr clause we just have to
7398 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007399 // pass its value.
7400 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007401 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007402 Pointers.push_back(Arg);
7403 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007404 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007405 return;
7406 }
7407
Paul Robinson78fb1322016-08-01 22:12:46 +00007408 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007409 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7410 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007411 assert(L.first == VD &&
7412 "We got information for the wrong declaration??");
7413 assert(!L.second.empty() &&
7414 "Not expecting declaration with no component lists.");
Alexey Bataevb3638132018-07-19 16:34:13 +00007415 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
7416 L.second, BasePointers, Pointers, Sizes,
7417 Types, PartialStruct, IsFirstComponentList,
7418 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007419 IsFirstComponentList = false;
7420 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007421 }
Samuel Antao86ace552016-04-27 22:40:57 +00007422
Alexey Bataevb3638132018-07-19 16:34:13 +00007423 /// Generate the base pointers, section pointers, sizes and map types
7424 /// associated with the declare target link variables.
7425 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7426 MapValuesArrayTy &Pointers,
7427 MapValuesArrayTy &Sizes,
7428 MapFlagsArrayTy &Types) const {
7429 // Map other list items in the map clause which are not captured variables
7430 // but "declare target link" global variables.,
7431 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7432 for (const auto &L : C->component_lists()) {
7433 if (!L.first)
7434 continue;
7435 const auto *VD = dyn_cast<VarDecl>(L.first);
7436 if (!VD)
7437 continue;
7438 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7439 isDeclareTargetDeclaration(VD);
7440 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7441 continue;
7442 StructRangeInfoTy PartialStruct;
7443 generateInfoForComponentList(
7444 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7445 Pointers, Sizes, Types, PartialStruct,
7446 /*IsFirstComponentList=*/true, C->isImplicit());
7447 assert(!PartialStruct.Base.isValid() &&
7448 "No partial structs for declare target link expected.");
7449 }
7450 }
Samuel Antao86ace552016-04-27 22:40:57 +00007451 }
Samuel Antaod486f842016-05-26 16:53:38 +00007452
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007453 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007454 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007455 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7456 const FieldDecl &RI, llvm::Value *CV,
7457 MapBaseValuesArrayTy &CurBasePointers,
7458 MapValuesArrayTy &CurPointers,
7459 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007460 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007461 // Do the default mapping.
7462 if (CI.capturesThis()) {
7463 CurBasePointers.push_back(CV);
7464 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007465 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007466 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7467 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007468 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007469 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007470 CurBasePointers.push_back(CV);
7471 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007472 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007473 // We have to signal to the runtime captures passed by value that are
7474 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007475 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007476 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7477 } else {
7478 // Pointers are implicitly mapped with a zero size and no flags
7479 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007480 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007481 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7482 }
7483 } else {
7484 assert(CI.capturesVariable() && "Expected captured reference.");
7485 CurBasePointers.push_back(CV);
7486 CurPointers.push_back(CV);
7487
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007488 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007489 QualType ElementType = PtrTy->getPointeeType();
7490 CurSizes.push_back(CGF.getTypeSize(ElementType));
7491 // The default map type for a scalar/complex type is 'to' because by
7492 // default the value doesn't have to be retrieved. For an aggregate
7493 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007494 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007495 }
George Rokos065755d2017-11-07 18:27:04 +00007496 // Every default map produces a single argument which is a target parameter.
7497 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007498
7499 // Add flag stating this is an implicit map.
7500 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007501 }
Samuel Antao86ace552016-04-27 22:40:57 +00007502};
Samuel Antaodf158d52016-04-27 22:58:19 +00007503
7504enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007505 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007506 /// from environment variables in the spec.
7507 OMP_DEVICEID_UNDEF = -1,
7508};
7509} // anonymous namespace
7510
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007511/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007512/// offloading runtime library. If there is no map or capture information,
7513/// return nullptr by reference.
7514static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007515emitOffloadingArrays(CodeGenFunction &CGF,
7516 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007517 MappableExprsHandler::MapValuesArrayTy &Pointers,
7518 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007519 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7520 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007521 CodeGenModule &CGM = CGF.CGM;
7522 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007523
Samuel Antaocc10b852016-07-28 14:23:26 +00007524 // Reset the array information.
7525 Info.clearArrayInfo();
7526 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007527
Samuel Antaocc10b852016-07-28 14:23:26 +00007528 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007529 // Detect if we have any capture size requiring runtime evaluation of the
7530 // size so that a constant array could be eventually used.
7531 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007532 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007533 if (!isa<llvm::Constant>(S)) {
7534 hasRuntimeEvaluationCaptureSize = true;
7535 break;
7536 }
7537
Samuel Antaocc10b852016-07-28 14:23:26 +00007538 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007539 QualType PointerArrayType =
7540 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7541 /*IndexTypeQuals=*/0);
7542
Samuel Antaocc10b852016-07-28 14:23:26 +00007543 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007544 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007545 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007546 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7547
7548 // If we don't have any VLA types or other types that require runtime
7549 // evaluation, we can use a constant array for the map sizes, otherwise we
7550 // need to fill up the arrays as we do for the pointers.
7551 if (hasRuntimeEvaluationCaptureSize) {
7552 QualType SizeArrayType = Ctx.getConstantArrayType(
7553 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7554 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007555 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007556 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7557 } else {
7558 // We expect all the sizes to be constant, so we collect them to create
7559 // a constant array.
7560 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007561 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007562 ConstSizes.push_back(cast<llvm::Constant>(S));
7563
7564 auto *SizesArrayInit = llvm::ConstantArray::get(
7565 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007566 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007567 auto *SizesArrayGbl = new llvm::GlobalVariable(
7568 CGM.getModule(), SizesArrayInit->getType(),
7569 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007570 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007571 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007572 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007573 }
7574
7575 // The map types are always constant so we don't need to generate code to
7576 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00007577 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
7578 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00007579 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00007580 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007581 std::string MaptypesName =
7582 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007583 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7584 CGM.getModule(), MapTypesArrayInit->getType(),
7585 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007586 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007587 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007588 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007589
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007590 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7591 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007592 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007593 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007594 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007595 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7596 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007597 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7598 CGF.Builder.CreateStore(BPVal, BPAddr);
7599
Samuel Antaocc10b852016-07-28 14:23:26 +00007600 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007601 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007602 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007603
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007604 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007605 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007606 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007607 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007608 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7609 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007610 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7611 CGF.Builder.CreateStore(PVal, PAddr);
7612
7613 if (hasRuntimeEvaluationCaptureSize) {
7614 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007615 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7616 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007617 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007618 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007619 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7620 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007621 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00007622 SAddr);
7623 }
7624 }
7625 }
7626}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007627/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00007628/// arrays of pointers, sizes and map types.
7629static void emitOffloadingArraysArgument(
7630 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7631 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007632 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007633 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007634 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007635 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007636 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7637 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007638 /*Idx0=*/0, /*Idx1=*/0);
7639 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007640 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7641 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007642 /*Idx0=*/0,
7643 /*Idx1=*/0);
7644 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007645 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007646 /*Idx0=*/0, /*Idx1=*/0);
7647 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007648 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007649 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007650 /*Idx0=*/0,
7651 /*Idx1=*/0);
7652 } else {
7653 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7654 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7655 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7656 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007657 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007658 }
Samuel Antao86ace552016-04-27 22:40:57 +00007659}
7660
Samuel Antaobed3c462015-10-02 16:14:20 +00007661void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7662 const OMPExecutableDirective &D,
7663 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007664 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007665 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007666 if (!CGF.HaveInsertPoint())
7667 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007668
Samuel Antaoee8fb302016-01-06 13:42:12 +00007669 assert(OutlinedFn && "Invalid outlined function!");
7670
Alexey Bataev8451efa2018-01-15 19:06:12 +00007671 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7672 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007673 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007674 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7675 PrePostActionTy &) {
7676 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7677 };
7678 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007679
Alexey Bataev8451efa2018-01-15 19:06:12 +00007680 CodeGenFunction::OMPTargetDataInfo InputInfo;
7681 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007682 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007683 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7684 &MapTypesArray, &CS, RequiresOuterTask,
7685 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007686 // On top of the arrays that were filled up, the target offloading call
7687 // takes as arguments the device id as well as the host pointer. The host
7688 // pointer is used by the runtime library to identify the current target
7689 // region, so it only has to be unique and not necessarily point to
7690 // anything. It could be the pointer to the outlined function that
7691 // implements the target region, but we aren't using that so that the
7692 // compiler doesn't need to keep that, and could therefore inline the host
7693 // function if proven worthwhile during optimization.
7694
Samuel Antaoee8fb302016-01-06 13:42:12 +00007695 // From this point on, we need to have an ID of the target region defined.
7696 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007697
7698 // Emit device ID if any.
7699 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007700 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007701 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007702 CGF.Int64Ty, /*isSigned=*/true);
7703 } else {
7704 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7705 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007706
Samuel Antaodf158d52016-04-27 22:58:19 +00007707 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007708 llvm::Value *PointerNum =
7709 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007710
Samuel Antaob68e2db2016-03-03 16:20:23 +00007711 // Return value of the runtime offloading call.
7712 llvm::Value *Return;
7713
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007714 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7715 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007716
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007717 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007718 // The target region is an outlined function launched by the runtime
7719 // via calls __tgt_target() or __tgt_target_teams().
7720 //
7721 // __tgt_target() launches a target region with one team and one thread,
7722 // executing a serial region. This master thread may in turn launch
7723 // more threads within its team upon encountering a parallel region,
7724 // however, no additional teams can be launched on the device.
7725 //
7726 // __tgt_target_teams() launches a target region with one or more teams,
7727 // each with one or more threads. This call is required for target
7728 // constructs such as:
7729 // 'target teams'
7730 // 'target' / 'teams'
7731 // 'target teams distribute parallel for'
7732 // 'target parallel'
7733 // and so on.
7734 //
7735 // Note that on the host and CPU targets, the runtime implementation of
7736 // these calls simply call the outlined function without forking threads.
7737 // The outlined functions themselves have runtime calls to
7738 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7739 // the compiler in emitTeamsCall() and emitParallelCall().
7740 //
7741 // In contrast, on the NVPTX target, the implementation of
7742 // __tgt_target_teams() launches a GPU kernel with the requested number
7743 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007744 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007745 // If we have NumTeams defined this means that we have an enclosed teams
7746 // region. Therefore we also expect to have NumThreads defined. These two
7747 // values should be defined in the presence of a teams directive,
7748 // regardless of having any clauses associated. If the user is using teams
7749 // but no clauses, these two values will be the default that should be
7750 // passed to the runtime library - a 32-bit integer with the value zero.
7751 assert(NumThreads && "Thread limit expression should be available along "
7752 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007753 llvm::Value *OffloadingArgs[] = {DeviceID,
7754 OutlinedFnID,
7755 PointerNum,
7756 InputInfo.BasePointersArray.getPointer(),
7757 InputInfo.PointersArray.getPointer(),
7758 InputInfo.SizesArray.getPointer(),
7759 MapTypesArray,
7760 NumTeams,
7761 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007762 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007763 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7764 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007765 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007766 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007767 llvm::Value *OffloadingArgs[] = {DeviceID,
7768 OutlinedFnID,
7769 PointerNum,
7770 InputInfo.BasePointersArray.getPointer(),
7771 InputInfo.PointersArray.getPointer(),
7772 InputInfo.SizesArray.getPointer(),
7773 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007774 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007775 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7776 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007777 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007778 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007779
Alexey Bataev2a007e02017-10-02 14:20:58 +00007780 // Check the error code and execute the host version if required.
7781 llvm::BasicBlock *OffloadFailedBlock =
7782 CGF.createBasicBlock("omp_offload.failed");
7783 llvm::BasicBlock *OffloadContBlock =
7784 CGF.createBasicBlock("omp_offload.cont");
7785 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7786 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7787
7788 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007789 if (RequiresOuterTask) {
7790 CapturedVars.clear();
7791 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7792 }
7793 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007794 CGF.EmitBranch(OffloadContBlock);
7795
7796 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007797 };
7798
Samuel Antaoee8fb302016-01-06 13:42:12 +00007799 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007800 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7801 RequiresOuterTask](CodeGenFunction &CGF,
7802 PrePostActionTy &) {
7803 if (RequiresOuterTask) {
7804 CapturedVars.clear();
7805 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7806 }
7807 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7808 };
7809
7810 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7811 &CapturedVars, RequiresOuterTask,
7812 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7813 // Fill up the arrays with all the captured variables.
7814 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7815 MappableExprsHandler::MapValuesArrayTy Pointers;
7816 MappableExprsHandler::MapValuesArrayTy Sizes;
7817 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7818
Alexey Bataev8451efa2018-01-15 19:06:12 +00007819 // Get mappable expression information.
7820 MappableExprsHandler MEHandler(D, CGF);
7821
7822 auto RI = CS.getCapturedRecordDecl()->field_begin();
7823 auto CV = CapturedVars.begin();
7824 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7825 CE = CS.capture_end();
7826 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007827 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7828 MappableExprsHandler::MapValuesArrayTy CurPointers;
7829 MappableExprsHandler::MapValuesArrayTy CurSizes;
7830 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7831 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00007832
7833 // VLA sizes are passed to the outlined region by copy and do not have map
7834 // information associated.
7835 if (CI->capturesVariableArrayType()) {
7836 CurBasePointers.push_back(*CV);
7837 CurPointers.push_back(*CV);
7838 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7839 // Copy to the device as an argument. No need to retrieve it.
7840 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7841 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7842 } else {
7843 // If we have any information in the map clause, we use it, otherwise we
7844 // just do a default mapping.
7845 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007846 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007847 if (CurBasePointers.empty())
7848 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7849 CurPointers, CurSizes, CurMapTypes);
7850 }
7851 // We expect to have at least an element of information for this capture.
7852 assert(!CurBasePointers.empty() &&
7853 "Non-existing map pointer for capture!");
7854 assert(CurBasePointers.size() == CurPointers.size() &&
7855 CurBasePointers.size() == CurSizes.size() &&
7856 CurBasePointers.size() == CurMapTypes.size() &&
7857 "Inconsistent map information sizes!");
7858
Alexey Bataevb3638132018-07-19 16:34:13 +00007859 // If there is an entry in PartialStruct it means we have a struct with
7860 // individual members mapped. Emit an extra combined entry.
7861 if (PartialStruct.Base.isValid())
7862 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
7863 CurMapTypes, PartialStruct);
7864
Alexey Bataev8451efa2018-01-15 19:06:12 +00007865 // We need to append the results of this capture to what we already have.
7866 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7867 Pointers.append(CurPointers.begin(), CurPointers.end());
7868 Sizes.append(CurSizes.begin(), CurSizes.end());
7869 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7870 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007871 // Map other list items in the map clause which are not captured variables
7872 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00007873 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
7874 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007875
7876 TargetDataInfo Info;
7877 // Fill up the arrays and create the arguments.
7878 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7879 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7880 Info.PointersArray, Info.SizesArray,
7881 Info.MapTypesArray, Info);
7882 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7883 InputInfo.BasePointersArray =
7884 Address(Info.BasePointersArray, CGM.getPointerAlign());
7885 InputInfo.PointersArray =
7886 Address(Info.PointersArray, CGM.getPointerAlign());
7887 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7888 MapTypesArray = Info.MapTypesArray;
7889 if (RequiresOuterTask)
7890 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7891 else
7892 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7893 };
7894
7895 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7896 CodeGenFunction &CGF, PrePostActionTy &) {
7897 if (RequiresOuterTask) {
7898 CodeGenFunction::OMPTargetDataInfo InputInfo;
7899 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7900 } else {
7901 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7902 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007903 };
7904
7905 // If we have a target function ID it means that we need to support
7906 // offloading, otherwise, just execute on the host. We need to execute on host
7907 // regardless of the conditional in the if clause if, e.g., the user do not
7908 // specify target triples.
7909 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007910 if (IfCond) {
7911 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7912 } else {
7913 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007914 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007915 }
7916 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007917 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007918 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007919 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007920}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007921
7922void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7923 StringRef ParentName) {
7924 if (!S)
7925 return;
7926
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007927 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007928 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007929 isa<OMPExecutableDirective>(S) &&
7930 isOpenMPTargetExecutionDirective(
7931 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007932
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007933 if (RequiresDeviceCodegen) {
7934 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007935 unsigned DeviceID;
7936 unsigned FileID;
7937 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007938 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007939 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007940
7941 // Is this a target region that should not be emitted as an entry point? If
7942 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007943 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7944 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007945 return;
7946
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007947 switch (E.getDirectiveKind()) {
7948 case OMPD_target:
7949 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
7950 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007951 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007952 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007953 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007954 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007955 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007956 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007957 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007958 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007959 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007960 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007961 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007962 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007963 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007964 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007965 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007966 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007967 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007968 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007969 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007970 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007971 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007972 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007973 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007974 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007975 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007976 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00007977 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007978 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00007979 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007980 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00007981 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7982 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007983 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00007984 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007985 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00007986 CodeGenFunction::
7987 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7988 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007989 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00007990 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007991 case OMPD_parallel:
7992 case OMPD_for:
7993 case OMPD_parallel_for:
7994 case OMPD_parallel_sections:
7995 case OMPD_for_simd:
7996 case OMPD_parallel_for_simd:
7997 case OMPD_cancel:
7998 case OMPD_cancellation_point:
7999 case OMPD_ordered:
8000 case OMPD_threadprivate:
8001 case OMPD_task:
8002 case OMPD_simd:
8003 case OMPD_sections:
8004 case OMPD_section:
8005 case OMPD_single:
8006 case OMPD_master:
8007 case OMPD_critical:
8008 case OMPD_taskyield:
8009 case OMPD_barrier:
8010 case OMPD_taskwait:
8011 case OMPD_taskgroup:
8012 case OMPD_atomic:
8013 case OMPD_flush:
8014 case OMPD_teams:
8015 case OMPD_target_data:
8016 case OMPD_target_exit_data:
8017 case OMPD_target_enter_data:
8018 case OMPD_distribute:
8019 case OMPD_distribute_simd:
8020 case OMPD_distribute_parallel_for:
8021 case OMPD_distribute_parallel_for_simd:
8022 case OMPD_teams_distribute:
8023 case OMPD_teams_distribute_simd:
8024 case OMPD_teams_distribute_parallel_for:
8025 case OMPD_teams_distribute_parallel_for_simd:
8026 case OMPD_target_update:
8027 case OMPD_declare_simd:
8028 case OMPD_declare_target:
8029 case OMPD_end_declare_target:
8030 case OMPD_declare_reduction:
8031 case OMPD_taskloop:
8032 case OMPD_taskloop_simd:
8033 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008034 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8035 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008036 return;
8037 }
8038
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008039 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008040 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008041 return;
8042
8043 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008044 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008045 return;
8046 }
8047
8048 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008049 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008050 S = L->getBody();
8051
8052 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008053 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008054 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008055}
8056
8057bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008058 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008059
8060 // If emitting code for the host, we do not process FD here. Instead we do
8061 // the normal code generation.
8062 if (!CGM.getLangOpts().OpenMPIsDevice)
8063 return false;
8064
8065 // Try to detect target regions in the function.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008066 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
Samuel Antaoee8fb302016-01-06 13:42:12 +00008067
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008068 // Do not to emit function if it is not marked as declare target.
Alexey Bataevfb388282018-05-01 14:09:46 +00008069 return !isDeclareTargetDeclaration(FD) &&
8070 AlreadyEmittedTargetFunctions.count(FD->getCanonicalDecl()) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008071}
8072
8073bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8074 if (!CGM.getLangOpts().OpenMPIsDevice)
8075 return false;
8076
8077 // Check if there are Ctors/Dtors in this declaration and look for target
8078 // regions in it. We use the complete variant to produce the kernel name
8079 // mangling.
8080 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008081 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8082 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008083 StringRef ParentName =
8084 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8085 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8086 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008087 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008088 StringRef ParentName =
8089 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8090 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8091 }
8092 }
8093
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008094 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008095 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev03f270c2018-03-30 18:31:07 +00008096 isDeclareTargetDeclaration(cast<VarDecl>(GD.getDecl()));
Alexey Bataev92327c52018-03-26 16:40:55 +00008097 return !Res || *Res == OMPDeclareTargetDeclAttr::MT_Link;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008098}
8099
Alexey Bataev03f270c2018-03-30 18:31:07 +00008100void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8101 llvm::Constant *Addr) {
8102 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8103 isDeclareTargetDeclaration(VD)) {
8104 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8105 StringRef VarName;
8106 CharUnits VarSize;
8107 llvm::GlobalValue::LinkageTypes Linkage;
8108 switch (*Res) {
8109 case OMPDeclareTargetDeclAttr::MT_To:
8110 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8111 VarName = CGM.getMangledName(VD);
8112 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8113 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
Alexey Bataev38235142018-07-31 16:40:15 +00008114 // Temp solution to prevent optimizations of the internal variables.
8115 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8116 std::string RefName = getName({VarName, "ref"});
8117 if (!CGM.GetGlobalValue(RefName)) {
8118 llvm::Constant *AddrRef =
8119 getOrCreateInternalVariable(Addr->getType(), RefName);
8120 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8121 GVAddrRef->setConstant(/*Val=*/true);
8122 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8123 GVAddrRef->setInitializer(Addr);
8124 CGM.addCompilerUsedGlobal(GVAddrRef);
8125 }
8126 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008127 break;
8128 case OMPDeclareTargetDeclAttr::MT_Link:
Alexey Bataevc52f01d2018-07-16 20:05:25 +00008129 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8130 if (CGM.getLangOpts().OpenMPIsDevice) {
8131 VarName = Addr->getName();
8132 Addr = nullptr;
8133 } else {
8134 VarName = getAddrOfDeclareTargetLink(VD).getName();
Alexey Bataev03f270c2018-03-30 18:31:07 +00008135 Addr =
8136 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8137 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008138 VarSize = CGM.getPointerSize();
8139 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8140 break;
8141 }
8142 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8143 VarName, Addr, VarSize, Flags, Linkage);
8144 }
8145}
8146
Samuel Antaoee8fb302016-01-06 13:42:12 +00008147bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008148 if (isa<FunctionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008149 return emitTargetFunctions(GD);
8150
8151 return emitTargetGlobalVariable(GD);
8152}
8153
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008154CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8155 CodeGenModule &CGM)
8156 : CGM(CGM) {
8157 if (CGM.getLangOpts().OpenMPIsDevice) {
8158 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8159 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8160 }
8161}
8162
8163CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8164 if (CGM.getLangOpts().OpenMPIsDevice)
8165 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8166}
8167
Alexey Bataev6d944102018-05-02 15:45:28 +00008168bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008169 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8170 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008171
Alexey Bataev6d944102018-05-02 15:45:28 +00008172 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008173 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00008174 // Do not to emit function if it is marked as declare target as it was already
8175 // emitted.
8176 if (isDeclareTargetDeclaration(D)) {
8177 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
8178 if (auto *F = dyn_cast_or_null<llvm::Function>(
Alexey Bataev6d944102018-05-02 15:45:28 +00008179 CGM.GetGlobalValue(CGM.getMangledName(GD))))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008180 return !F->isDeclaration();
8181 return false;
8182 }
8183 return true;
8184 }
8185
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008186 return !AlreadyEmittedTargetFunctions.insert(FD).second;
8187}
8188
Samuel Antaoee8fb302016-01-06 13:42:12 +00008189llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8190 // If we have offloading in the current module, we need to emit the entries
8191 // now and register the offloading descriptor.
8192 createOffloadEntriesAndInfoMetadata();
8193
8194 // Create and register the offloading binary descriptors. This is the main
8195 // entity that captures all the information about offloading in the current
8196 // compilation unit.
8197 return createOffloadingBinaryDescriptorRegistration();
8198}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008199
8200void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8201 const OMPExecutableDirective &D,
8202 SourceLocation Loc,
8203 llvm::Value *OutlinedFn,
8204 ArrayRef<llvm::Value *> CapturedVars) {
8205 if (!CGF.HaveInsertPoint())
8206 return;
8207
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008208 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008209 CodeGenFunction::RunCleanupsScope Scope(CGF);
8210
8211 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8212 llvm::Value *Args[] = {
8213 RTLoc,
8214 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8215 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8216 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8217 RealArgs.append(std::begin(Args), std::end(Args));
8218 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8219
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008220 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008221 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8222}
8223
8224void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008225 const Expr *NumTeams,
8226 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008227 SourceLocation Loc) {
8228 if (!CGF.HaveInsertPoint())
8229 return;
8230
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008231 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008232
Carlo Bertollic6872252016-04-04 15:55:02 +00008233 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008234 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008235 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8236 CGF.CGM.Int32Ty, /* isSigned = */ true)
8237 : CGF.Builder.getInt32(0);
8238
8239 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008240 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008241 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8242 CGF.CGM.Int32Ty, /* isSigned = */ true)
8243 : CGF.Builder.getInt32(0);
8244
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008245 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008246 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8247 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008248 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8249 PushNumTeamsArgs);
8250}
Samuel Antaodf158d52016-04-27 22:58:19 +00008251
Samuel Antaocc10b852016-07-28 14:23:26 +00008252void CGOpenMPRuntime::emitTargetDataCalls(
8253 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8254 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008255 if (!CGF.HaveInsertPoint())
8256 return;
8257
Samuel Antaocc10b852016-07-28 14:23:26 +00008258 // Action used to replace the default codegen action and turn privatization
8259 // off.
8260 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008261
8262 // Generate the code for the opening of the data environment. Capture all the
8263 // arguments of the runtime call by reference because they are used in the
8264 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008265 auto &&BeginThenGen = [this, &D, Device, &Info,
8266 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008267 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008268 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008269 MappableExprsHandler::MapValuesArrayTy Pointers;
8270 MappableExprsHandler::MapValuesArrayTy Sizes;
8271 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8272
8273 // Get map clause information.
8274 MappableExprsHandler MCHandler(D, CGF);
8275 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008276
8277 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008278 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008279
8280 llvm::Value *BasePointersArrayArg = nullptr;
8281 llvm::Value *PointersArrayArg = nullptr;
8282 llvm::Value *SizesArrayArg = nullptr;
8283 llvm::Value *MapTypesArrayArg = nullptr;
8284 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008285 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008286
8287 // Emit device ID if any.
8288 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008289 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008290 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008291 CGF.Int64Ty, /*isSigned=*/true);
8292 } else {
8293 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8294 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008295
8296 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008297 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008298
8299 llvm::Value *OffloadingArgs[] = {
8300 DeviceID, PointerNum, BasePointersArrayArg,
8301 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008302 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008303 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008304
8305 // If device pointer privatization is required, emit the body of the region
8306 // here. It will have to be duplicated: with and without privatization.
8307 if (!Info.CaptureDeviceAddrMap.empty())
8308 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008309 };
8310
8311 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008312 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8313 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008314 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008315
8316 llvm::Value *BasePointersArrayArg = nullptr;
8317 llvm::Value *PointersArrayArg = nullptr;
8318 llvm::Value *SizesArrayArg = nullptr;
8319 llvm::Value *MapTypesArrayArg = nullptr;
8320 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008321 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008322
8323 // Emit device ID if any.
8324 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008325 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008326 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008327 CGF.Int64Ty, /*isSigned=*/true);
8328 } else {
8329 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8330 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008331
8332 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008333 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008334
8335 llvm::Value *OffloadingArgs[] = {
8336 DeviceID, PointerNum, BasePointersArrayArg,
8337 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008338 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008339 OffloadingArgs);
8340 };
8341
Samuel Antaocc10b852016-07-28 14:23:26 +00008342 // If we need device pointer privatization, we need to emit the body of the
8343 // region with no privatization in the 'else' branch of the conditional.
8344 // Otherwise, we don't have to do anything.
8345 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8346 PrePostActionTy &) {
8347 if (!Info.CaptureDeviceAddrMap.empty()) {
8348 CodeGen.setAction(NoPrivAction);
8349 CodeGen(CGF);
8350 }
8351 };
8352
8353 // We don't have to do anything to close the region if the if clause evaluates
8354 // to false.
8355 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008356
8357 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008358 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008359 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008360 RegionCodeGenTy RCG(BeginThenGen);
8361 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008362 }
8363
Samuel Antaocc10b852016-07-28 14:23:26 +00008364 // If we don't require privatization of device pointers, we emit the body in
8365 // between the runtime calls. This avoids duplicating the body code.
8366 if (Info.CaptureDeviceAddrMap.empty()) {
8367 CodeGen.setAction(NoPrivAction);
8368 CodeGen(CGF);
8369 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008370
8371 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008372 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008373 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008374 RegionCodeGenTy RCG(EndThenGen);
8375 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008376 }
8377}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008378
Samuel Antao8d2d7302016-05-26 18:30:22 +00008379void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008380 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8381 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008382 if (!CGF.HaveInsertPoint())
8383 return;
8384
Samuel Antao8dd66282016-04-27 23:14:30 +00008385 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008386 isa<OMPTargetExitDataDirective>(D) ||
8387 isa<OMPTargetUpdateDirective>(D)) &&
8388 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008389
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008390 CodeGenFunction::OMPTargetDataInfo InputInfo;
8391 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008392 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008393 auto &&ThenGen = [this, &D, Device, &InputInfo,
8394 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008395 // Emit device ID if any.
8396 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008397 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008398 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008399 CGF.Int64Ty, /*isSigned=*/true);
8400 } else {
8401 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8402 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008403
8404 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008405 llvm::Constant *PointerNum =
8406 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008407
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008408 llvm::Value *OffloadingArgs[] = {DeviceID,
8409 PointerNum,
8410 InputInfo.BasePointersArray.getPointer(),
8411 InputInfo.PointersArray.getPointer(),
8412 InputInfo.SizesArray.getPointer(),
8413 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008414
Samuel Antao8d2d7302016-05-26 18:30:22 +00008415 // Select the right runtime function call for each expected standalone
8416 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008417 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008418 OpenMPRTLFunction RTLFn;
8419 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008420 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008421 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8422 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008423 break;
8424 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008425 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8426 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008427 break;
8428 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008429 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8430 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008431 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008432 case OMPD_parallel:
8433 case OMPD_for:
8434 case OMPD_parallel_for:
8435 case OMPD_parallel_sections:
8436 case OMPD_for_simd:
8437 case OMPD_parallel_for_simd:
8438 case OMPD_cancel:
8439 case OMPD_cancellation_point:
8440 case OMPD_ordered:
8441 case OMPD_threadprivate:
8442 case OMPD_task:
8443 case OMPD_simd:
8444 case OMPD_sections:
8445 case OMPD_section:
8446 case OMPD_single:
8447 case OMPD_master:
8448 case OMPD_critical:
8449 case OMPD_taskyield:
8450 case OMPD_barrier:
8451 case OMPD_taskwait:
8452 case OMPD_taskgroup:
8453 case OMPD_atomic:
8454 case OMPD_flush:
8455 case OMPD_teams:
8456 case OMPD_target_data:
8457 case OMPD_distribute:
8458 case OMPD_distribute_simd:
8459 case OMPD_distribute_parallel_for:
8460 case OMPD_distribute_parallel_for_simd:
8461 case OMPD_teams_distribute:
8462 case OMPD_teams_distribute_simd:
8463 case OMPD_teams_distribute_parallel_for:
8464 case OMPD_teams_distribute_parallel_for_simd:
8465 case OMPD_declare_simd:
8466 case OMPD_declare_target:
8467 case OMPD_end_declare_target:
8468 case OMPD_declare_reduction:
8469 case OMPD_taskloop:
8470 case OMPD_taskloop_simd:
8471 case OMPD_target:
8472 case OMPD_target_simd:
8473 case OMPD_target_teams_distribute:
8474 case OMPD_target_teams_distribute_simd:
8475 case OMPD_target_teams_distribute_parallel_for:
8476 case OMPD_target_teams_distribute_parallel_for_simd:
8477 case OMPD_target_teams:
8478 case OMPD_target_parallel:
8479 case OMPD_target_parallel_for:
8480 case OMPD_target_parallel_for_simd:
8481 case OMPD_unknown:
8482 llvm_unreachable("Unexpected standalone target data directive.");
8483 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008484 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008485 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008486 };
8487
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008488 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8489 CodeGenFunction &CGF, PrePostActionTy &) {
8490 // Fill up the arrays with all the mapped variables.
8491 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8492 MappableExprsHandler::MapValuesArrayTy Pointers;
8493 MappableExprsHandler::MapValuesArrayTy Sizes;
8494 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008495
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008496 // Get map clause information.
8497 MappableExprsHandler MEHandler(D, CGF);
8498 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8499
8500 TargetDataInfo Info;
8501 // Fill up the arrays and create the arguments.
8502 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8503 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8504 Info.PointersArray, Info.SizesArray,
8505 Info.MapTypesArray, Info);
8506 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8507 InputInfo.BasePointersArray =
8508 Address(Info.BasePointersArray, CGM.getPointerAlign());
8509 InputInfo.PointersArray =
8510 Address(Info.PointersArray, CGM.getPointerAlign());
8511 InputInfo.SizesArray =
8512 Address(Info.SizesArray, CGM.getPointerAlign());
8513 MapTypesArray = Info.MapTypesArray;
8514 if (D.hasClausesOfKind<OMPDependClause>())
8515 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8516 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008517 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008518 };
8519
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008520 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008521 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8522 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008523 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008524 RegionCodeGenTy ThenRCG(TargetThenGen);
8525 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008526 }
8527}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008528
8529namespace {
8530 /// Kind of parameter in a function with 'declare simd' directive.
8531 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8532 /// Attribute set of the parameter.
8533 struct ParamAttrTy {
8534 ParamKindTy Kind = Vector;
8535 llvm::APSInt StrideOrArg;
8536 llvm::APSInt Alignment;
8537 };
8538} // namespace
8539
8540static unsigned evaluateCDTSize(const FunctionDecl *FD,
8541 ArrayRef<ParamAttrTy> ParamAttrs) {
8542 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8543 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8544 // of that clause. The VLEN value must be power of 2.
8545 // In other case the notion of the function`s "characteristic data type" (CDT)
8546 // is used to compute the vector length.
8547 // CDT is defined in the following order:
8548 // a) For non-void function, the CDT is the return type.
8549 // b) If the function has any non-uniform, non-linear parameters, then the
8550 // CDT is the type of the first such parameter.
8551 // c) If the CDT determined by a) or b) above is struct, union, or class
8552 // type which is pass-by-value (except for the type that maps to the
8553 // built-in complex data type), the characteristic data type is int.
8554 // d) If none of the above three cases is applicable, the CDT is int.
8555 // The VLEN is then determined based on the CDT and the size of vector
8556 // register of that ISA for which current vector version is generated. The
8557 // VLEN is computed using the formula below:
8558 // VLEN = sizeof(vector_register) / sizeof(CDT),
8559 // where vector register size specified in section 3.2.1 Registers and the
8560 // Stack Frame of original AMD64 ABI document.
8561 QualType RetType = FD->getReturnType();
8562 if (RetType.isNull())
8563 return 0;
8564 ASTContext &C = FD->getASTContext();
8565 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008566 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008567 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008568 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008569 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008570 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008571 if (ParamAttrs[Offset].Kind == Vector)
8572 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8573 ++Offset;
8574 }
8575 if (CDT.isNull()) {
8576 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8577 if (ParamAttrs[I + Offset].Kind == Vector) {
8578 CDT = FD->getParamDecl(I)->getType();
8579 break;
8580 }
8581 }
8582 }
8583 }
8584 if (CDT.isNull())
8585 CDT = C.IntTy;
8586 CDT = CDT->getCanonicalTypeUnqualified();
8587 if (CDT->isRecordType() || CDT->isUnionType())
8588 CDT = C.IntTy;
8589 return C.getTypeSize(CDT);
8590}
8591
8592static void
8593emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008594 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008595 ArrayRef<ParamAttrTy> ParamAttrs,
8596 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8597 struct ISADataTy {
8598 char ISA;
8599 unsigned VecRegSize;
8600 };
8601 ISADataTy ISAData[] = {
8602 {
8603 'b', 128
8604 }, // SSE
8605 {
8606 'c', 256
8607 }, // AVX
8608 {
8609 'd', 256
8610 }, // AVX2
8611 {
8612 'e', 512
8613 }, // AVX512
8614 };
8615 llvm::SmallVector<char, 2> Masked;
8616 switch (State) {
8617 case OMPDeclareSimdDeclAttr::BS_Undefined:
8618 Masked.push_back('N');
8619 Masked.push_back('M');
8620 break;
8621 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8622 Masked.push_back('N');
8623 break;
8624 case OMPDeclareSimdDeclAttr::BS_Inbranch:
8625 Masked.push_back('M');
8626 break;
8627 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008628 for (char Mask : Masked) {
8629 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008630 SmallString<256> Buffer;
8631 llvm::raw_svector_ostream Out(Buffer);
8632 Out << "_ZGV" << Data.ISA << Mask;
8633 if (!VLENVal) {
8634 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8635 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008636 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008637 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008638 }
8639 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008640 switch (ParamAttr.Kind){
8641 case LinearWithVarStride:
8642 Out << 's' << ParamAttr.StrideOrArg;
8643 break;
8644 case Linear:
8645 Out << 'l';
8646 if (!!ParamAttr.StrideOrArg)
8647 Out << ParamAttr.StrideOrArg;
8648 break;
8649 case Uniform:
8650 Out << 'u';
8651 break;
8652 case Vector:
8653 Out << 'v';
8654 break;
8655 }
8656 if (!!ParamAttr.Alignment)
8657 Out << 'a' << ParamAttr.Alignment;
8658 }
8659 Out << '_' << Fn->getName();
8660 Fn->addFnAttr(Out.str());
8661 }
8662 }
8663}
8664
8665void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8666 llvm::Function *Fn) {
8667 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008668 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008669 // Map params to their positions in function decl.
8670 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8671 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008672 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008673 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008674 for (const ParmVarDecl *P : FD->parameters()) {
8675 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008676 ++ParamPos;
8677 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008678 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008679 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008680 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8681 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008682 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008683 E = E->IgnoreParenImpCasts();
8684 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008685 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008686 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008687 } else {
8688 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8689 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008690 Pos = ParamPositions[PVD];
8691 }
8692 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008693 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008694 // Get alignment info.
8695 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008696 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008697 E = E->IgnoreParenImpCasts();
8698 unsigned Pos;
8699 QualType ParmTy;
8700 if (isa<CXXThisExpr>(E)) {
8701 Pos = ParamPositions[FD];
8702 ParmTy = E->getType();
8703 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008704 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8705 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008706 Pos = ParamPositions[PVD];
8707 ParmTy = PVD->getType();
8708 }
8709 ParamAttrs[Pos].Alignment =
8710 (*NI)
8711 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008712 : llvm::APSInt::getUnsigned(
8713 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8714 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008715 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008716 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008717 // Mark linear parameters.
8718 auto SI = Attr->steps_begin();
8719 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008720 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008721 E = E->IgnoreParenImpCasts();
8722 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008723 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008724 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008725 } else {
8726 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8727 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008728 Pos = ParamPositions[PVD];
8729 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008730 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008731 ParamAttr.Kind = Linear;
8732 if (*SI) {
8733 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8734 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008735 if (const auto *DRE =
8736 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8737 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008738 ParamAttr.Kind = LinearWithVarStride;
8739 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8740 ParamPositions[StridePVD->getCanonicalDecl()]);
8741 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008742 }
8743 }
8744 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008745 ++SI;
8746 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008747 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008748 llvm::APSInt VLENVal;
8749 if (const Expr *VLEN = Attr->getSimdlen())
8750 VLENVal = VLEN->EvaluateKnownConstInt(C);
8751 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8752 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8753 CGM.getTriple().getArch() == llvm::Triple::x86_64)
8754 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008755 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008756 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008757 }
8758}
Alexey Bataev8b427062016-05-25 12:36:08 +00008759
8760namespace {
8761/// Cleanup action for doacross support.
8762class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8763public:
8764 static const int DoacrossFinArgs = 2;
8765
8766private:
8767 llvm::Value *RTLFn;
8768 llvm::Value *Args[DoacrossFinArgs];
8769
8770public:
8771 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8772 : RTLFn(RTLFn) {
8773 assert(CallArgs.size() == DoacrossFinArgs);
8774 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8775 }
8776 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8777 if (!CGF.HaveInsertPoint())
8778 return;
8779 CGF.EmitRuntimeCall(RTLFn, Args);
8780 }
8781};
8782} // namespace
8783
8784void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8785 const OMPLoopDirective &D) {
8786 if (!CGF.HaveInsertPoint())
8787 return;
8788
8789 ASTContext &C = CGM.getContext();
8790 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8791 RecordDecl *RD;
8792 if (KmpDimTy.isNull()) {
8793 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
8794 // kmp_int64 lo; // lower
8795 // kmp_int64 up; // upper
8796 // kmp_int64 st; // stride
8797 // };
8798 RD = C.buildImplicitRecord("kmp_dim");
8799 RD->startDefinition();
8800 addFieldToRecordDecl(C, RD, Int64Ty);
8801 addFieldToRecordDecl(C, RD, Int64Ty);
8802 addFieldToRecordDecl(C, RD, Int64Ty);
8803 RD->completeDefinition();
8804 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008805 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008806 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008807 }
Alexey Bataev8b427062016-05-25 12:36:08 +00008808
8809 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8810 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8811 enum { LowerFD = 0, UpperFD, StrideFD };
8812 // Fill dims with data.
8813 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8814 // dims.upper = num_iterations;
8815 LValue UpperLVal =
8816 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8817 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8818 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8819 Int64Ty, D.getNumIterations()->getExprLoc());
8820 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8821 // dims.stride = 1;
8822 LValue StrideLVal =
8823 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8824 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8825 StrideLVal);
8826
8827 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8828 // kmp_int32 num_dims, struct kmp_dim * dims);
8829 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8830 getThreadID(CGF, D.getLocStart()),
8831 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8832 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8833 DimsAddr.getPointer(), CGM.VoidPtrTy)};
8834
8835 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8836 CGF.EmitRuntimeCall(RTLFn, Args);
8837 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8838 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8839 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8840 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8841 llvm::makeArrayRef(FiniArgs));
8842}
8843
8844void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8845 const OMPDependClause *C) {
8846 QualType Int64Ty =
8847 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8848 const Expr *CounterVal = C->getCounterValue();
8849 assert(CounterVal);
8850 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8851 CounterVal->getType(), Int64Ty,
8852 CounterVal->getExprLoc());
8853 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8854 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8855 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8856 getThreadID(CGF, C->getLocStart()),
8857 CntAddr.getPointer()};
8858 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008859 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00008860 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008861 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008862 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8863 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8864 }
8865 CGF.EmitRuntimeCall(RTLFn, Args);
8866}
8867
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008868void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8869 llvm::Value *Callee,
8870 ArrayRef<llvm::Value *> Args) const {
8871 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008872 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8873
8874 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008875 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008876 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008877 return;
8878 }
8879 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008880 CGF.EmitRuntimeCall(Callee, Args);
8881}
8882
8883void CGOpenMPRuntime::emitOutlinedFunctionCall(
8884 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8885 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008886 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008887}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008888
8889Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8890 const VarDecl *NativeParam,
8891 const VarDecl *TargetParam) const {
8892 return CGF.GetAddrOfLocalVar(NativeParam);
8893}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008894
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00008895Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8896 const VarDecl *VD) {
8897 return Address::invalid();
8898}
8899
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008900llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8901 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8902 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8903 llvm_unreachable("Not supported in SIMD-only mode");
8904}
8905
8906llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8907 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8908 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8909 llvm_unreachable("Not supported in SIMD-only mode");
8910}
8911
8912llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8913 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8914 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8915 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8916 bool Tied, unsigned &NumberOfParts) {
8917 llvm_unreachable("Not supported in SIMD-only mode");
8918}
8919
8920void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8921 SourceLocation Loc,
8922 llvm::Value *OutlinedFn,
8923 ArrayRef<llvm::Value *> CapturedVars,
8924 const Expr *IfCond) {
8925 llvm_unreachable("Not supported in SIMD-only mode");
8926}
8927
8928void CGOpenMPSIMDRuntime::emitCriticalRegion(
8929 CodeGenFunction &CGF, StringRef CriticalName,
8930 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8931 const Expr *Hint) {
8932 llvm_unreachable("Not supported in SIMD-only mode");
8933}
8934
8935void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8936 const RegionCodeGenTy &MasterOpGen,
8937 SourceLocation Loc) {
8938 llvm_unreachable("Not supported in SIMD-only mode");
8939}
8940
8941void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8942 SourceLocation Loc) {
8943 llvm_unreachable("Not supported in SIMD-only mode");
8944}
8945
8946void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8947 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8948 SourceLocation Loc) {
8949 llvm_unreachable("Not supported in SIMD-only mode");
8950}
8951
8952void CGOpenMPSIMDRuntime::emitSingleRegion(
8953 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8954 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8955 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8956 ArrayRef<const Expr *> AssignmentOps) {
8957 llvm_unreachable("Not supported in SIMD-only mode");
8958}
8959
8960void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8961 const RegionCodeGenTy &OrderedOpGen,
8962 SourceLocation Loc,
8963 bool IsThreads) {
8964 llvm_unreachable("Not supported in SIMD-only mode");
8965}
8966
8967void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8968 SourceLocation Loc,
8969 OpenMPDirectiveKind Kind,
8970 bool EmitChecks,
8971 bool ForceSimpleCall) {
8972 llvm_unreachable("Not supported in SIMD-only mode");
8973}
8974
8975void CGOpenMPSIMDRuntime::emitForDispatchInit(
8976 CodeGenFunction &CGF, SourceLocation Loc,
8977 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8978 bool Ordered, const DispatchRTInput &DispatchValues) {
8979 llvm_unreachable("Not supported in SIMD-only mode");
8980}
8981
8982void CGOpenMPSIMDRuntime::emitForStaticInit(
8983 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8984 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8985 llvm_unreachable("Not supported in SIMD-only mode");
8986}
8987
8988void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8989 CodeGenFunction &CGF, SourceLocation Loc,
8990 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8991 llvm_unreachable("Not supported in SIMD-only mode");
8992}
8993
8994void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8995 SourceLocation Loc,
8996 unsigned IVSize,
8997 bool IVSigned) {
8998 llvm_unreachable("Not supported in SIMD-only mode");
8999}
9000
9001void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9002 SourceLocation Loc,
9003 OpenMPDirectiveKind DKind) {
9004 llvm_unreachable("Not supported in SIMD-only mode");
9005}
9006
9007llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9008 SourceLocation Loc,
9009 unsigned IVSize, bool IVSigned,
9010 Address IL, Address LB,
9011 Address UB, Address ST) {
9012 llvm_unreachable("Not supported in SIMD-only mode");
9013}
9014
9015void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9016 llvm::Value *NumThreads,
9017 SourceLocation Loc) {
9018 llvm_unreachable("Not supported in SIMD-only mode");
9019}
9020
9021void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9022 OpenMPProcBindClauseKind ProcBind,
9023 SourceLocation Loc) {
9024 llvm_unreachable("Not supported in SIMD-only mode");
9025}
9026
9027Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9028 const VarDecl *VD,
9029 Address VDAddr,
9030 SourceLocation Loc) {
9031 llvm_unreachable("Not supported in SIMD-only mode");
9032}
9033
9034llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9035 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9036 CodeGenFunction *CGF) {
9037 llvm_unreachable("Not supported in SIMD-only mode");
9038}
9039
9040Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9041 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9042 llvm_unreachable("Not supported in SIMD-only mode");
9043}
9044
9045void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9046 ArrayRef<const Expr *> Vars,
9047 SourceLocation Loc) {
9048 llvm_unreachable("Not supported in SIMD-only mode");
9049}
9050
9051void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9052 const OMPExecutableDirective &D,
9053 llvm::Value *TaskFunction,
9054 QualType SharedsTy, Address Shareds,
9055 const Expr *IfCond,
9056 const OMPTaskDataTy &Data) {
9057 llvm_unreachable("Not supported in SIMD-only mode");
9058}
9059
9060void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9061 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9062 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9063 const Expr *IfCond, const OMPTaskDataTy &Data) {
9064 llvm_unreachable("Not supported in SIMD-only mode");
9065}
9066
9067void CGOpenMPSIMDRuntime::emitReduction(
9068 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9069 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9070 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9071 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9072 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9073 ReductionOps, Options);
9074}
9075
9076llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9077 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9078 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9079 llvm_unreachable("Not supported in SIMD-only mode");
9080}
9081
9082void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9083 SourceLocation Loc,
9084 ReductionCodeGen &RCG,
9085 unsigned N) {
9086 llvm_unreachable("Not supported in SIMD-only mode");
9087}
9088
9089Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9090 SourceLocation Loc,
9091 llvm::Value *ReductionsPtr,
9092 LValue SharedLVal) {
9093 llvm_unreachable("Not supported in SIMD-only mode");
9094}
9095
9096void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9097 SourceLocation Loc) {
9098 llvm_unreachable("Not supported in SIMD-only mode");
9099}
9100
9101void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9102 CodeGenFunction &CGF, SourceLocation Loc,
9103 OpenMPDirectiveKind CancelRegion) {
9104 llvm_unreachable("Not supported in SIMD-only mode");
9105}
9106
9107void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9108 SourceLocation Loc, const Expr *IfCond,
9109 OpenMPDirectiveKind CancelRegion) {
9110 llvm_unreachable("Not supported in SIMD-only mode");
9111}
9112
9113void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9114 const OMPExecutableDirective &D, StringRef ParentName,
9115 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9116 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9117 llvm_unreachable("Not supported in SIMD-only mode");
9118}
9119
9120void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9121 const OMPExecutableDirective &D,
9122 llvm::Value *OutlinedFn,
9123 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009124 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009125 llvm_unreachable("Not supported in SIMD-only mode");
9126}
9127
9128bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9129 llvm_unreachable("Not supported in SIMD-only mode");
9130}
9131
9132bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9133 llvm_unreachable("Not supported in SIMD-only mode");
9134}
9135
9136bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9137 return false;
9138}
9139
9140llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9141 return nullptr;
9142}
9143
9144void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9145 const OMPExecutableDirective &D,
9146 SourceLocation Loc,
9147 llvm::Value *OutlinedFn,
9148 ArrayRef<llvm::Value *> CapturedVars) {
9149 llvm_unreachable("Not supported in SIMD-only mode");
9150}
9151
9152void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9153 const Expr *NumTeams,
9154 const Expr *ThreadLimit,
9155 SourceLocation Loc) {
9156 llvm_unreachable("Not supported in SIMD-only mode");
9157}
9158
9159void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9160 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9161 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9162 llvm_unreachable("Not supported in SIMD-only mode");
9163}
9164
9165void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9166 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9167 const Expr *Device) {
9168 llvm_unreachable("Not supported in SIMD-only mode");
9169}
9170
9171void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
9172 const OMPLoopDirective &D) {
9173 llvm_unreachable("Not supported in SIMD-only mode");
9174}
9175
9176void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9177 const OMPDependClause *C) {
9178 llvm_unreachable("Not supported in SIMD-only mode");
9179}
9180
9181const VarDecl *
9182CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9183 const VarDecl *NativeParam) const {
9184 llvm_unreachable("Not supported in SIMD-only mode");
9185}
9186
9187Address
9188CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9189 const VarDecl *NativeParam,
9190 const VarDecl *TargetParam) const {
9191 llvm_unreachable("Not supported in SIMD-only mode");
9192}
9193