blob: f05a086879b8d5717dbd0dcd966d01a5ab5ea885 [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
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
Alexey Bataev36bf0112015-03-10 05:15:26 +000016#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000017#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000018#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000020#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/Value.h"
24#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000025#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000026
27using namespace clang;
28using namespace CodeGen;
29
Benjamin Kramerc52193f2014-10-10 13:57:57 +000030namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000031/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000032class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
33public:
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000034 CGOpenMPRegionInfo(const OMPExecutableDirective &D, const CapturedStmt &CS)
35 : CGCapturedStmtInfo(CS, CR_OpenMP), Directive(D) {}
Alexey Bataev18095712014-10-10 12:19:54 +000036
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000037 CGOpenMPRegionInfo(const OMPExecutableDirective &D)
38 : CGCapturedStmtInfo(CR_OpenMP), Directive(D) {}
39
40 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000041 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000042 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000043
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000044 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000045 /// \return LValue for thread id variable. This LValue always has type int32*.
46 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000047
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000048 /// \brief Emit the captured statement body.
49 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
50
Alexey Bataev18095712014-10-10 12:19:54 +000051 static bool classof(const CGCapturedStmtInfo *Info) {
52 return Info->getKind() == CR_OpenMP;
53 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000054protected:
55 /// \brief OpenMP executable directive associated with the region.
56 const OMPExecutableDirective &Directive;
57};
Alexey Bataev18095712014-10-10 12:19:54 +000058
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000059/// \brief API for captured statement code generation in OpenMP constructs.
60class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
61public:
62 CGOpenMPOutlinedRegionInfo(const OMPExecutableDirective &D,
63 const CapturedStmt &CS, const VarDecl *ThreadIDVar)
64 : CGOpenMPRegionInfo(D, CS), ThreadIDVar(ThreadIDVar) {
65 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
66 }
67 /// \brief Get a variable or parameter for storing global thread id
68 /// inside OpenMP construct.
69 virtual const VarDecl *getThreadIDVariable() const override {
70 return ThreadIDVar;
71 }
Alexey Bataev18095712014-10-10 12:19:54 +000072 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +000073 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +000074
75private:
76 /// \brief A variable or parameter storing global thread id for OpenMP
77 /// constructs.
78 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079};
80
Alexey Bataev62b63b12015-03-10 07:28:44 +000081/// \brief API for captured statement code generation in OpenMP constructs.
82class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
83public:
84 CGOpenMPTaskOutlinedRegionInfo(const OMPExecutableDirective &D,
85 const CapturedStmt &CS,
86 const VarDecl *ThreadIDVar,
87 const VarDecl *PartIDVar)
88 : CGOpenMPRegionInfo(D, CS), ThreadIDVar(ThreadIDVar),
89 PartIDVar(PartIDVar) {
90 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
91 }
92 /// \brief Get a variable or parameter for storing global thread id
93 /// inside OpenMP construct.
94 virtual const VarDecl *getThreadIDVariable() const override {
95 return ThreadIDVar;
96 }
97
98 /// \brief Get an LValue for the current ThreadID variable.
99 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
100
101 /// \brief Emit the captured statement body.
102 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
103
104 /// \brief Get the name of the capture helper.
105 StringRef getHelperName() const override { return ".omp_outlined."; }
106
107private:
108 /// \brief A variable or parameter storing global thread id for OpenMP
109 /// constructs.
110 const VarDecl *ThreadIDVar;
111 /// \brief A variable or parameter storing part id for OpenMP tasking
112 /// constructs.
113 const VarDecl *PartIDVar;
114};
115
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000116/// \brief API for inlined captured statement code generation in OpenMP
117/// constructs.
118class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
119public:
120 CGOpenMPInlinedRegionInfo(const OMPExecutableDirective &D,
121 CodeGenFunction::CGCapturedStmtInfo *OldCSI)
122 : CGOpenMPRegionInfo(D), OldCSI(OldCSI),
123 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
124 // \brief Retrieve the value of the context parameter.
125 virtual llvm::Value *getContextValue() const override {
126 if (OuterRegionInfo)
127 return OuterRegionInfo->getContextValue();
128 llvm_unreachable("No context value for inlined OpenMP region");
129 }
130 /// \brief Lookup the captured field decl for a variable.
131 virtual const FieldDecl *lookup(const VarDecl *VD) const override {
132 if (OuterRegionInfo)
133 return OuterRegionInfo->lookup(VD);
134 llvm_unreachable("Trying to reference VarDecl that is neither local nor "
135 "captured in outer OpenMP region");
136 }
137 virtual FieldDecl *getThisFieldDecl() const override {
138 if (OuterRegionInfo)
139 return OuterRegionInfo->getThisFieldDecl();
140 return nullptr;
141 }
142 /// \brief Get a variable or parameter for storing global thread id
143 /// inside OpenMP construct.
144 virtual const VarDecl *getThreadIDVariable() const override {
145 if (OuterRegionInfo)
146 return OuterRegionInfo->getThreadIDVariable();
147 return nullptr;
148 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000149
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000150 /// \brief Get the name of the capture helper.
151 virtual StringRef getHelperName() const override {
152 llvm_unreachable("No helper name for inlined OpenMP construct");
153 }
154
155 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
156
157private:
158 /// \brief CodeGen info about outer OpenMP region.
159 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
160 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000161};
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000162} // namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000163
164LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
165 return CGF.MakeNaturalAlignAddrLValue(
Alexey Bataev62b63b12015-03-10 07:28:44 +0000166 CGF.Builder.CreateAlignedLoad(
167 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
168 CGF.PointerAlignInBytes),
169 getThreadIDVariable()
170 ->getType()
171 ->castAs<PointerType>()
172 ->getPointeeType());
Alexey Bataev18095712014-10-10 12:19:54 +0000173}
174
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000175void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt *S) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000176 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataev03b340a2014-10-21 03:16:40 +0000177 CGF.EmitOMPPrivateClause(Directive, PrivateScope);
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000178 CGF.EmitOMPFirstprivateClause(Directive, PrivateScope);
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000179 if (PrivateScope.Privatize())
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000180 // Emit implicit barrier to synchronize threads and avoid data races.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000181 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, Directive.getLocStart(),
Alexey Bataevf2685682015-03-30 04:30:22 +0000182 OMPD_unknown);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000183 CGCapturedStmtInfo::EmitBody(CGF, S);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000184}
185
Alexey Bataev62b63b12015-03-10 07:28:44 +0000186LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
187 CodeGenFunction &CGF) {
188 return CGF.MakeNaturalAlignAddrLValue(
189 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
190 getThreadIDVariable()->getType());
191}
192
193void CGOpenMPTaskOutlinedRegionInfo::EmitBody(CodeGenFunction &CGF,
194 const Stmt *S) {
195 if (PartIDVar) {
196 // TODO: emit code for untied tasks.
197 }
198 CGCapturedStmtInfo::EmitBody(CGF, S);
199}
200
Alexey Bataev9959db52014-05-06 10:08:46 +0000201CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataev62b63b12015-03-10 07:28:44 +0000202 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000203 IdentTy = llvm::StructType::create(
204 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
205 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000206 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000207 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000208 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
209 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000210 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000211 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Alexey Bataev9959db52014-05-06 10:08:46 +0000212}
213
Alexey Bataev91797552015-03-18 04:13:55 +0000214void CGOpenMPRuntime::clear() {
215 InternalVars.clear();
216}
217
Alexey Bataev9959db52014-05-06 10:08:46 +0000218llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000219CGOpenMPRuntime::emitOutlinedFunction(const OMPExecutableDirective &D,
220 const VarDecl *ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000221 assert(ThreadIDVar->getType()->isPointerType() &&
222 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000223 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
224 CodeGenFunction CGF(CGM, true);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000225 CGOpenMPOutlinedRegionInfo CGInfo(D, *CS, ThreadIDVar);
Alexey Bataev18095712014-10-10 12:19:54 +0000226 CGF.CapturedStmtInfo = &CGInfo;
227 return CGF.GenerateCapturedStmtFunction(*CS);
228}
229
230llvm::Value *
Alexey Bataev62b63b12015-03-10 07:28:44 +0000231CGOpenMPRuntime::emitTaskOutlinedFunction(const OMPExecutableDirective &D,
232 const VarDecl *ThreadIDVar,
233 const VarDecl *PartIDVar) {
234 assert(!ThreadIDVar->getType()->isPointerType() &&
235 "thread id variable must be of type kmp_int32 for tasks");
236 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
237 CodeGenFunction CGF(CGM, true);
238 CGOpenMPTaskOutlinedRegionInfo CGInfo(D, *CS, ThreadIDVar, PartIDVar);
239 CGF.CapturedStmtInfo = &CGInfo;
240 return CGF.GenerateCapturedStmtFunction(*CS);
241}
242
243llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000244CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000245 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000246 if (!Entry) {
247 if (!DefaultOpenMPPSource) {
248 // Initialize default location for psource field of ident_t structure of
249 // all ident_t objects. Format is ";file;function;line;column;;".
250 // Taken from
251 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
252 DefaultOpenMPPSource =
253 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
254 DefaultOpenMPPSource =
255 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
256 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000257 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
258 CGM.getModule(), IdentTy, /*isConstant*/ true,
259 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000260 DefaultOpenMPLocation->setUnnamedAddr(true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000261
262 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000263 llvm::Constant *Values[] = {Zero,
264 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
265 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000266 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
267 DefaultOpenMPLocation->setInitializer(Init);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000268 OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000269 return DefaultOpenMPLocation;
270 }
271 return Entry;
272}
273
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000274llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
275 SourceLocation Loc,
276 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000277 // If no debug info is generated - return global default location.
278 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
279 Loc.isInvalid())
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000280 return getOrCreateDefaultLocation(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000281
282 assert(CGF.CurFn && "No function in current CodeGenFunction.");
283
Alexey Bataev9959db52014-05-06 10:08:46 +0000284 llvm::Value *LocValue = nullptr;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000285 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
286 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataev18095712014-10-10 12:19:54 +0000287 LocValue = I->second.DebugLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +0000288 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
289 // GetOpenMPThreadID was called before this routine.
290 if (LocValue == nullptr) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000291 // Generate "ident_t .kmpc_loc.addr;"
292 llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
Alexey Bataev9959db52014-05-06 10:08:46 +0000293 AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
Alexey Bataev18095712014-10-10 12:19:54 +0000294 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
295 Elem.second.DebugLoc = AI;
Alexey Bataev9959db52014-05-06 10:08:46 +0000296 LocValue = AI;
297
298 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
299 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000300 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataev9959db52014-05-06 10:08:46 +0000301 llvm::ConstantExpr::getSizeOf(IdentTy),
302 CGM.PointerAlignInBytes);
303 }
304
305 // char **psource = &.kmpc_loc_<flags>.addr.psource;
David Blaikie1ed728c2015-04-05 22:45:47 +0000306 auto *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(IdentTy, LocValue, 0,
307 IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000308
Alexey Bataevf002aca2014-05-30 05:48:40 +0000309 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
310 if (OMPDebugLoc == nullptr) {
311 SmallString<128> Buffer2;
312 llvm::raw_svector_ostream OS2(Buffer2);
313 // Build debug location
314 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
315 OS2 << ";" << PLoc.getFilename() << ";";
316 if (const FunctionDecl *FD =
317 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
318 OS2 << FD->getQualifiedNameAsString();
319 }
320 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
321 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
322 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000323 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000324 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000325 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
326
Alexey Bataev9959db52014-05-06 10:08:46 +0000327 return LocValue;
328}
329
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000330llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
331 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000332 assert(CGF.CurFn && "No function in current CodeGenFunction.");
333
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000334 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000335 // Check whether we've already cached a load of the thread id in this
336 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000337 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000338 if (I != OpenMPLocThreadIDMap.end()) {
339 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000340 if (ThreadID != nullptr)
341 return ThreadID;
342 }
343 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000344 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000345 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000346 // Check if this an outlined function with thread id passed as argument.
347 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000348 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
349 // If value loaded in entry block, cache it and use it everywhere in
350 // function.
351 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
352 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
353 Elem.second.ThreadID = ThreadID;
354 }
355 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000356 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000357 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000358
359 // This is not an outlined function region - need to call __kmpc_int32
360 // kmpc_global_thread_num(ident_t *loc).
361 // Generate thread id value and cache this value for use across the
362 // function.
363 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
364 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
365 ThreadID =
366 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
367 emitUpdateLocation(CGF, Loc));
368 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
369 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000370 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000371}
372
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000373void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000374 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000375 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
376 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000377}
378
379llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
380 return llvm::PointerType::getUnqual(IdentTy);
381}
382
383llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
384 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
385}
386
387llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000388CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000389 llvm::Constant *RTLFn = nullptr;
390 switch (Function) {
391 case OMPRTL__kmpc_fork_call: {
392 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
393 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000394 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
395 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000396 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000397 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000398 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
399 break;
400 }
401 case OMPRTL__kmpc_global_thread_num: {
402 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000403 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000404 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000405 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000406 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
407 break;
408 }
Alexey Bataev97720002014-11-11 04:05:39 +0000409 case OMPRTL__kmpc_threadprivate_cached: {
410 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
411 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
412 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
413 CGM.VoidPtrTy, CGM.SizeTy,
414 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
415 llvm::FunctionType *FnTy =
416 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
417 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
418 break;
419 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000420 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000421 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
422 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000423 llvm::Type *TypeParams[] = {
424 getIdentTyPointerTy(), CGM.Int32Ty,
425 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
426 llvm::FunctionType *FnTy =
427 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
428 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
429 break;
430 }
Alexey Bataev97720002014-11-11 04:05:39 +0000431 case OMPRTL__kmpc_threadprivate_register: {
432 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
433 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
434 // typedef void *(*kmpc_ctor)(void *);
435 auto KmpcCtorTy =
436 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
437 /*isVarArg*/ false)->getPointerTo();
438 // typedef void *(*kmpc_cctor)(void *, void *);
439 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
440 auto KmpcCopyCtorTy =
441 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
442 /*isVarArg*/ false)->getPointerTo();
443 // typedef void (*kmpc_dtor)(void *);
444 auto KmpcDtorTy =
445 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
446 ->getPointerTo();
447 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
448 KmpcCopyCtorTy, KmpcDtorTy};
449 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
450 /*isVarArg*/ false);
451 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
452 break;
453 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000454 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000455 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
456 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000457 llvm::Type *TypeParams[] = {
458 getIdentTyPointerTy(), CGM.Int32Ty,
459 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
460 llvm::FunctionType *FnTy =
461 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
462 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
463 break;
464 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000465 case OMPRTL__kmpc_cancel_barrier: {
466 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
467 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000468 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
469 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000470 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
471 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000472 break;
473 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000474 case OMPRTL__kmpc_for_static_fini: {
475 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
476 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
477 llvm::FunctionType *FnTy =
478 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
479 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
480 break;
481 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000482 case OMPRTL__kmpc_push_num_threads: {
483 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
484 // kmp_int32 num_threads)
485 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
486 CGM.Int32Ty};
487 llvm::FunctionType *FnTy =
488 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
489 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
490 break;
491 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000492 case OMPRTL__kmpc_serialized_parallel: {
493 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
494 // global_tid);
495 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
496 llvm::FunctionType *FnTy =
497 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
498 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
499 break;
500 }
501 case OMPRTL__kmpc_end_serialized_parallel: {
502 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
503 // global_tid);
504 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
505 llvm::FunctionType *FnTy =
506 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
507 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
508 break;
509 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000510 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000511 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000512 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
513 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000514 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000515 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
516 break;
517 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000518 case OMPRTL__kmpc_master: {
519 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
520 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
521 llvm::FunctionType *FnTy =
522 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
523 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
524 break;
525 }
526 case OMPRTL__kmpc_end_master: {
527 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
528 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
529 llvm::FunctionType *FnTy =
530 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
531 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
532 break;
533 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000534 case OMPRTL__kmpc_omp_taskyield: {
535 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
536 // int end_part);
537 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
538 llvm::FunctionType *FnTy =
539 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
540 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
541 break;
542 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000543 case OMPRTL__kmpc_single: {
544 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
545 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
546 llvm::FunctionType *FnTy =
547 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
548 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
549 break;
550 }
551 case OMPRTL__kmpc_end_single: {
552 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
553 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
554 llvm::FunctionType *FnTy =
555 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
556 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
557 break;
558 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000559 case OMPRTL__kmpc_omp_task_alloc: {
560 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
561 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
562 // kmp_routine_entry_t *task_entry);
563 assert(KmpRoutineEntryPtrTy != nullptr &&
564 "Type kmp_routine_entry_t must be created.");
565 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
566 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
567 // Return void * and then cast to particular kmp_task_t type.
568 llvm::FunctionType *FnTy =
569 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
570 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
571 break;
572 }
573 case OMPRTL__kmpc_omp_task: {
574 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
575 // *new_task);
576 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
577 CGM.VoidPtrTy};
578 llvm::FunctionType *FnTy =
579 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
580 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
581 break;
582 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000583 case OMPRTL__kmpc_copyprivate: {
584 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
585 // kmp_int32 cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
586 // kmp_int32 didit);
587 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
588 auto *CpyFnTy =
589 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
590 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
591 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
592 CGM.Int32Ty};
593 llvm::FunctionType *FnTy =
594 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
595 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
596 break;
597 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000598 }
599 return RTLFn;
600}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000601
Alexander Musman21212e42015-03-13 10:38:23 +0000602llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
603 bool IVSigned) {
604 assert((IVSize == 32 || IVSize == 64) &&
605 "IV size is not compatible with the omp runtime");
606 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
607 : "__kmpc_for_static_init_4u")
608 : (IVSigned ? "__kmpc_for_static_init_8"
609 : "__kmpc_for_static_init_8u");
610 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
611 auto PtrTy = llvm::PointerType::getUnqual(ITy);
612 llvm::Type *TypeParams[] = {
613 getIdentTyPointerTy(), // loc
614 CGM.Int32Ty, // tid
615 CGM.Int32Ty, // schedtype
616 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
617 PtrTy, // p_lower
618 PtrTy, // p_upper
619 PtrTy, // p_stride
620 ITy, // incr
621 ITy // chunk
622 };
623 llvm::FunctionType *FnTy =
624 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
625 return CGM.CreateRuntimeFunction(FnTy, Name);
626}
627
Alexander Musman92bdaab2015-03-12 13:37:50 +0000628llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
629 bool IVSigned) {
630 assert((IVSize == 32 || IVSize == 64) &&
631 "IV size is not compatible with the omp runtime");
632 auto Name =
633 IVSize == 32
634 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
635 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
636 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
637 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
638 CGM.Int32Ty, // tid
639 CGM.Int32Ty, // schedtype
640 ITy, // lower
641 ITy, // upper
642 ITy, // stride
643 ITy // chunk
644 };
645 llvm::FunctionType *FnTy =
646 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
647 return CGM.CreateRuntimeFunction(FnTy, Name);
648}
649
650llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
651 bool IVSigned) {
652 assert((IVSize == 32 || IVSize == 64) &&
653 "IV size is not compatible with the omp runtime");
654 auto Name =
655 IVSize == 32
656 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
657 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
658 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
659 auto PtrTy = llvm::PointerType::getUnqual(ITy);
660 llvm::Type *TypeParams[] = {
661 getIdentTyPointerTy(), // loc
662 CGM.Int32Ty, // tid
663 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
664 PtrTy, // p_lower
665 PtrTy, // p_upper
666 PtrTy // p_stride
667 };
668 llvm::FunctionType *FnTy =
669 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
670 return CGM.CreateRuntimeFunction(FnTy, Name);
671}
672
Alexey Bataev97720002014-11-11 04:05:39 +0000673llvm::Constant *
674CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
675 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000676 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000677 Twine(CGM.getMangledName(VD)) + ".cache.");
678}
679
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000680llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
681 const VarDecl *VD,
682 llvm::Value *VDAddr,
683 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000684 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000685 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000686 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
687 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
688 getOrCreateThreadPrivateCache(VD)};
689 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000690 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000691}
692
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000693void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000694 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
695 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
696 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
697 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000698 auto OMPLoc = emitUpdateLocation(CGF, Loc);
699 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000700 OMPLoc);
701 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
702 // to register constructor/destructor for variable.
703 llvm::Value *Args[] = {OMPLoc,
704 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
705 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000706 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000707 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000708}
709
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000710llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000711 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
712 bool PerformInit, CodeGenFunction *CGF) {
713 VD = VD->getDefinition(CGM.getContext());
714 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
715 ThreadPrivateWithDefinition.insert(VD);
716 QualType ASTTy = VD->getType();
717
718 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
719 auto Init = VD->getAnyInitializer();
720 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
721 // Generate function that re-emits the declaration's initializer into the
722 // threadprivate copy of the variable VD
723 CodeGenFunction CtorCGF(CGM);
724 FunctionArgList Args;
725 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
726 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
727 Args.push_back(&Dst);
728
729 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
730 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
731 /*isVariadic=*/false);
732 auto FTy = CGM.getTypes().GetFunctionType(FI);
733 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
734 FTy, ".__kmpc_global_ctor_.", Loc);
735 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
736 Args, SourceLocation());
737 auto ArgVal = CtorCGF.EmitLoadOfScalar(
738 CtorCGF.GetAddrOfLocalVar(&Dst),
739 /*Volatile=*/false, CGM.PointerAlignInBytes,
740 CGM.getContext().VoidPtrTy, Dst.getLocation());
741 auto Arg = CtorCGF.Builder.CreatePointerCast(
742 ArgVal,
743 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
744 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
745 /*IsInitializer=*/true);
746 ArgVal = CtorCGF.EmitLoadOfScalar(
747 CtorCGF.GetAddrOfLocalVar(&Dst),
748 /*Volatile=*/false, CGM.PointerAlignInBytes,
749 CGM.getContext().VoidPtrTy, Dst.getLocation());
750 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
751 CtorCGF.FinishFunction();
752 Ctor = Fn;
753 }
754 if (VD->getType().isDestructedType() != QualType::DK_none) {
755 // Generate function that emits destructor call for the threadprivate copy
756 // of the variable VD
757 CodeGenFunction DtorCGF(CGM);
758 FunctionArgList Args;
759 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
760 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
761 Args.push_back(&Dst);
762
763 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
764 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
765 /*isVariadic=*/false);
766 auto FTy = CGM.getTypes().GetFunctionType(FI);
767 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
768 FTy, ".__kmpc_global_dtor_.", Loc);
769 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
770 SourceLocation());
771 auto ArgVal = DtorCGF.EmitLoadOfScalar(
772 DtorCGF.GetAddrOfLocalVar(&Dst),
773 /*Volatile=*/false, CGM.PointerAlignInBytes,
774 CGM.getContext().VoidPtrTy, Dst.getLocation());
775 DtorCGF.emitDestroy(ArgVal, ASTTy,
776 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
777 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
778 DtorCGF.FinishFunction();
779 Dtor = Fn;
780 }
781 // Do not emit init function if it is not required.
782 if (!Ctor && !Dtor)
783 return nullptr;
784
785 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
786 auto CopyCtorTy =
787 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
788 /*isVarArg=*/false)->getPointerTo();
789 // Copying constructor for the threadprivate variable.
790 // Must be NULL - reserved by runtime, but currently it requires that this
791 // parameter is always NULL. Otherwise it fires assertion.
792 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
793 if (Ctor == nullptr) {
794 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
795 /*isVarArg=*/false)->getPointerTo();
796 Ctor = llvm::Constant::getNullValue(CtorTy);
797 }
798 if (Dtor == nullptr) {
799 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
800 /*isVarArg=*/false)->getPointerTo();
801 Dtor = llvm::Constant::getNullValue(DtorTy);
802 }
803 if (!CGF) {
804 auto InitFunctionTy =
805 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
806 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
807 InitFunctionTy, ".__omp_threadprivate_init_.");
808 CodeGenFunction InitCGF(CGM);
809 FunctionArgList ArgList;
810 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
811 CGM.getTypes().arrangeNullaryFunction(), ArgList,
812 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000813 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000814 InitCGF.FinishFunction();
815 return InitFunction;
816 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000817 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000818 }
819 return nullptr;
820}
821
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000822void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
823 llvm::Value *OutlinedFn,
824 llvm::Value *CapturedStruct) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000825 // Build call __kmpc_fork_call(loc, 1, microtask, captured_struct/*context*/)
826 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000827 emitUpdateLocation(CGF, Loc),
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000828 CGF.Builder.getInt32(1), // Number of arguments after 'microtask' argument
829 // (there is only one additional argument - 'context')
830 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
831 CGF.EmitCastToVoidPtr(CapturedStruct)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000832 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000833 CGF.EmitRuntimeCall(RTLFn, Args);
834}
835
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000836void CGOpenMPRuntime::emitSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
837 llvm::Value *OutlinedFn,
838 llvm::Value *CapturedStruct) {
839 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000840 // Build calls:
841 // __kmpc_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000842 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), ThreadID};
843 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
844 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000845
846 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000847 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000848 auto Int32Ty =
849 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
850 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
851 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
852 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
853 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
854
855 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000856 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
857 CGF.EmitRuntimeCall(
858 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000859}
860
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +0000861// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +0000862// thread-ID variable (it is passed in a first argument of the outlined function
863// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
864// regular serial code region, get thread ID by calling kmp_int32
865// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
866// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000867llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +0000868 SourceLocation Loc) {
869 if (auto OMPRegionInfo =
870 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000871 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +0000872 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000873
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000874 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000875 auto Int32Ty =
876 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
877 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
878 CGF.EmitStoreOfScalar(ThreadID,
879 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
880
881 return ThreadIDTemp;
882}
883
Alexey Bataev97720002014-11-11 04:05:39 +0000884llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000885CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +0000886 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000887 SmallString<256> Buffer;
888 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +0000889 Out << Name;
890 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +0000891 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
892 if (Elem.second) {
893 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +0000894 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +0000895 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +0000896 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000897
David Blaikie13156b62014-11-19 03:06:06 +0000898 return Elem.second = new llvm::GlobalVariable(
899 CGM.getModule(), Ty, /*IsConstant*/ false,
900 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
901 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +0000902}
903
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000904llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +0000905 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000906 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000907}
908
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000909void CGOpenMPRuntime::emitCriticalRegion(
Alexey Bataev75ddfab2014-12-01 11:32:38 +0000910 CodeGenFunction &CGF, StringRef CriticalName,
911 const std::function<void()> &CriticalOpGen, SourceLocation Loc) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000912 auto RegionLock = getCriticalRegionLock(CriticalName);
Alexey Bataev75ddfab2014-12-01 11:32:38 +0000913 // __kmpc_critical(ident_t *, gtid, Lock);
914 // CriticalOpGen();
915 // __kmpc_end_critical(ident_t *, gtid, Lock);
916 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000917 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
918 RegionLock};
919 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev75ddfab2014-12-01 11:32:38 +0000920 CriticalOpGen();
921 // Build a call to __kmpc_end_critical
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000922 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000923}
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000924
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000925static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
926 const std::function<void()> &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +0000927 llvm::Value *CallBool = CGF.EmitScalarConversion(
928 IfCond,
929 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
930 CGF.getContext().BoolTy);
931
932 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
933 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
934 // Generate the branch (If-stmt)
935 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
936 CGF.EmitBlock(ThenBlock);
937 BodyOpGen();
938 // Emit the rest of bblocks/branches
939 CGF.EmitBranch(ContBlock);
940 CGF.EmitBlock(ContBlock, true);
941}
942
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000943void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
944 const std::function<void()> &MasterOpGen,
945 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +0000946 // if(__kmpc_master(ident_t *, gtid)) {
947 // MasterOpGen();
948 // __kmpc_end_master(ident_t *, gtid);
949 // }
950 // Prepare arguments and build a call to __kmpc_master
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000951 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
952 auto *IsMaster =
953 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
954 emitIfStmt(CGF, IsMaster, [&]() -> void {
Alexey Bataev8d690652014-12-04 07:23:53 +0000955 MasterOpGen();
956 // Build a call to __kmpc_end_master.
957 // OpenMP [1.2.2 OpenMP Language Terminology]
958 // For C/C++, an executable statement, possibly compound, with a single
959 // entry at the top and a single exit at the bottom, or an OpenMP construct.
960 // * Access to the structured block must not be the result of a branch.
961 // * The point of exit cannot be a branch out of the structured block.
962 // * The point of entry must not be a call to setjmp().
963 // * longjmp() and throw() must not violate the entry/exit criteria.
964 // * An expression statement, iteration statement, selection statement, or
965 // try block is considered to be a structured block if the corresponding
966 // compound statement obtained by enclosing it in { and } would be a
967 // structured block.
968 // It is analyzed in Sema, so we can just call __kmpc_end_master() on
969 // fallthrough rather than pushing a normal cleanup for it.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000970 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_master), Args);
Alexey Bataev8d690652014-12-04 07:23:53 +0000971 });
972}
973
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000974void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
975 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +0000976 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
977 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000978 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +0000979 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000980 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +0000981}
982
Alexey Bataeva63048e2015-03-23 06:18:07 +0000983static llvm::Value *emitCopyprivateCopyFunction(
984 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> SrcExprs,
985 ArrayRef<const Expr *> DstExprs, ArrayRef<const Expr *> AssignmentOps) {
986 auto &C = CGM.getContext();
987 // void copy_func(void *LHSArg, void *RHSArg);
988 FunctionArgList Args;
989 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
990 C.VoidPtrTy);
991 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
992 C.VoidPtrTy);
993 Args.push_back(&LHSArg);
994 Args.push_back(&RHSArg);
995 FunctionType::ExtInfo EI;
996 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
997 C.VoidTy, Args, EI, /*isVariadic=*/false);
998 auto *Fn = llvm::Function::Create(
999 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1000 ".omp.copyprivate.copy_func", &CGM.getModule());
1001 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1002 CodeGenFunction CGF(CGM);
1003 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1004 // Dst = (void*[n])(LHSArg);
1005 // Src = (void*[n])(RHSArg);
1006 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1007 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1008 CGF.PointerAlignInBytes),
1009 ArgsType);
1010 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1011 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1012 CGF.PointerAlignInBytes),
1013 ArgsType);
1014 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1015 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1016 // ...
1017 // *(Typen*)Dst[n] = *(Typen*)Src[n];
1018 CodeGenFunction::OMPPrivateScope Scope(CGF);
1019 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
1020 Scope.addPrivate(
1021 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
1022 [&]() -> llvm::Value *{
1023 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
David Blaikie1ed728c2015-04-05 22:45:47 +00001024 CGF.Builder.CreateAlignedLoad(
1025 CGF.Builder.CreateStructGEP(nullptr, RHS, I),
1026 CGM.PointerAlignInBytes),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001027 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1028 });
1029 Scope.addPrivate(
1030 cast<VarDecl>(cast<DeclRefExpr>(DstExprs[I])->getDecl()),
1031 [&]() -> llvm::Value *{
1032 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
David Blaikie1ed728c2015-04-05 22:45:47 +00001033 CGF.Builder.CreateAlignedLoad(
1034 CGF.Builder.CreateStructGEP(nullptr, LHS, I),
1035 CGM.PointerAlignInBytes),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001036 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1037 });
1038 }
1039 Scope.Privatize();
1040 for (auto *E : AssignmentOps) {
1041 CGF.EmitIgnoredExpr(E);
1042 }
1043 Scope.ForceCleanup();
1044 CGF.FinishFunction();
1045 return Fn;
1046}
1047
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001048void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
1049 const std::function<void()> &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001050 SourceLocation Loc,
1051 ArrayRef<const Expr *> CopyprivateVars,
1052 ArrayRef<const Expr *> SrcExprs,
1053 ArrayRef<const Expr *> DstExprs,
1054 ArrayRef<const Expr *> AssignmentOps) {
1055 assert(CopyprivateVars.size() == SrcExprs.size() &&
1056 CopyprivateVars.size() == DstExprs.size() &&
1057 CopyprivateVars.size() == AssignmentOps.size());
1058 auto &C = CGM.getContext();
1059 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001060 // if(__kmpc_single(ident_t *, gtid)) {
1061 // SingleOpGen();
1062 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001063 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001064 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001065 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1066 // <copy_func>, did_it);
1067
1068 llvm::AllocaInst *DidIt = nullptr;
1069 if (!CopyprivateVars.empty()) {
1070 // int32 did_it = 0;
1071 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1072 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
1073 CGF.InitTempAlloca(DidIt, CGF.Builder.getInt32(0));
1074 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001075 // Prepare arguments and build a call to __kmpc_single
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001076 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1077 auto *IsSingle =
1078 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
1079 emitIfStmt(CGF, IsSingle, [&]() -> void {
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001080 SingleOpGen();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001081 if (DidIt) {
1082 // did_it = 1;
1083 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1084 DidIt->getAlignment());
1085 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001086 // Build a call to __kmpc_end_single.
1087 // OpenMP [1.2.2 OpenMP Language Terminology]
1088 // For C/C++, an executable statement, possibly compound, with a single
1089 // entry at the top and a single exit at the bottom, or an OpenMP construct.
1090 // * Access to the structured block must not be the result of a branch.
1091 // * The point of exit cannot be a branch out of the structured block.
1092 // * The point of entry must not be a call to setjmp().
1093 // * longjmp() and throw() must not violate the entry/exit criteria.
1094 // * An expression statement, iteration statement, selection statement, or
1095 // try block is considered to be a structured block if the corresponding
1096 // compound statement obtained by enclosing it in { and } would be a
1097 // structured block.
1098 // It is analyzed in Sema, so we can just call __kmpc_end_single() on
1099 // fallthrough rather than pushing a normal cleanup for it.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001100 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_single), Args);
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001101 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001102 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1103 // <copy_func>, did_it);
1104 if (DidIt) {
1105 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1106 auto CopyprivateArrayTy =
1107 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1108 /*IndexTypeQuals=*/0);
1109 // Create a list of all private variables for copyprivate.
1110 auto *CopyprivateList =
1111 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1112 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001113 auto *Elem = CGF.Builder.CreateStructGEP(
1114 CopyprivateList->getAllocatedType(), CopyprivateList, I);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001115 CGF.Builder.CreateAlignedStore(
1116 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1117 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1118 Elem, CGM.PointerAlignInBytes);
1119 }
1120 // Build function that copies private values from single region to all other
1121 // threads in the corresponding parallel region.
1122 auto *CpyFn = emitCopyprivateCopyFunction(
1123 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
1124 SrcExprs, DstExprs, AssignmentOps);
1125 auto *BufSize = CGF.Builder.getInt32(
1126 C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
1127 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1128 CGF.VoidPtrTy);
1129 auto *DidItVal =
1130 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1131 llvm::Value *Args[] = {
1132 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1133 getThreadID(CGF, Loc), // i32 <gtid>
1134 BufSize, // i32 <buf_size>
1135 CL, // void *<copyprivate list>
1136 CpyFn, // void (*) (void *, void *) <copy_func>
1137 DidItVal // i32 did_it
1138 };
1139 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1140 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001141}
1142
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001143void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf2685682015-03-30 04:30:22 +00001144 OpenMPDirectiveKind Kind) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001145 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001146 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1147 if (Kind == OMPD_for) {
1148 Flags =
1149 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1150 } else if (Kind == OMPD_sections) {
1151 Flags = static_cast<OpenMPLocationFlags>(Flags |
1152 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1153 } else if (Kind == OMPD_single) {
1154 Flags =
1155 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1156 } else if (Kind == OMPD_barrier) {
1157 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1158 } else {
1159 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1160 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001161 // Build call __kmpc_cancel_barrier(loc, thread_id);
1162 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1163 // one provides the same functionality and adds initial support for
1164 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1165 // is provided default by the runtime library so it safe to make such
1166 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001167 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1168 getThreadID(CGF, Loc)};
1169 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001170}
1171
Alexander Musmanc6388682014-12-15 07:07:06 +00001172/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1173/// the enum sched_type in kmp.h).
1174enum OpenMPSchedType {
1175 /// \brief Lower bound for default (unordered) versions.
1176 OMP_sch_lower = 32,
1177 OMP_sch_static_chunked = 33,
1178 OMP_sch_static = 34,
1179 OMP_sch_dynamic_chunked = 35,
1180 OMP_sch_guided_chunked = 36,
1181 OMP_sch_runtime = 37,
1182 OMP_sch_auto = 38,
1183 /// \brief Lower bound for 'ordered' versions.
1184 OMP_ord_lower = 64,
1185 /// \brief Lower bound for 'nomerge' versions.
1186 OMP_nm_lower = 160,
1187};
1188
1189/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1190static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
1191 bool Chunked) {
1192 switch (ScheduleKind) {
1193 case OMPC_SCHEDULE_static:
1194 return Chunked ? OMP_sch_static_chunked : OMP_sch_static;
1195 case OMPC_SCHEDULE_dynamic:
1196 return OMP_sch_dynamic_chunked;
1197 case OMPC_SCHEDULE_guided:
1198 return OMP_sch_guided_chunked;
1199 case OMPC_SCHEDULE_auto:
1200 return OMP_sch_auto;
1201 case OMPC_SCHEDULE_runtime:
1202 return OMP_sch_runtime;
1203 case OMPC_SCHEDULE_unknown:
1204 assert(!Chunked && "chunk was specified but schedule kind not known");
1205 return OMP_sch_static;
1206 }
1207 llvm_unreachable("Unexpected runtime schedule");
1208}
1209
1210bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1211 bool Chunked) const {
1212 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
1213 return Schedule == OMP_sch_static;
1214}
1215
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001216bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
1217 auto Schedule = getRuntimeSchedule(ScheduleKind, /* Chunked */ false);
1218 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1219 return Schedule != OMP_sch_static;
1220}
1221
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001222void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1223 OpenMPScheduleClauseKind ScheduleKind,
1224 unsigned IVSize, bool IVSigned,
1225 llvm::Value *IL, llvm::Value *LB,
1226 llvm::Value *UB, llvm::Value *ST,
1227 llvm::Value *Chunk) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001228 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunk != nullptr);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001229 if (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked) {
1230 // Call __kmpc_dispatch_init(
1231 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1232 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1233 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001234
Alexander Musman92bdaab2015-03-12 13:37:50 +00001235 // If the Chunk was not specified in the clause - use default value 1.
1236 if (Chunk == nullptr)
1237 Chunk = CGF.Builder.getIntN(IVSize, 1);
1238 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1239 getThreadID(CGF, Loc),
1240 CGF.Builder.getInt32(Schedule), // Schedule type
1241 CGF.Builder.getIntN(IVSize, 0), // Lower
1242 UB, // Upper
1243 CGF.Builder.getIntN(IVSize, 1), // Stride
1244 Chunk // Chunk
1245 };
1246 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1247 } else {
1248 // Call __kmpc_for_static_init(
1249 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1250 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1251 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1252 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1253 if (Chunk == nullptr) {
1254 assert(Schedule == OMP_sch_static &&
1255 "expected static non-chunked schedule");
1256 // If the Chunk was not specified in the clause - use default value 1.
1257 Chunk = CGF.Builder.getIntN(IVSize, 1);
1258 } else
1259 assert(Schedule == OMP_sch_static_chunked &&
1260 "expected static chunked schedule");
1261 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1262 getThreadID(CGF, Loc),
1263 CGF.Builder.getInt32(Schedule), // Schedule type
1264 IL, // &isLastIter
1265 LB, // &LB
1266 UB, // &UB
1267 ST, // &Stride
1268 CGF.Builder.getIntN(IVSize, 1), // Incr
1269 Chunk // Chunk
1270 };
Alexander Musman21212e42015-03-13 10:38:23 +00001271 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001272 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001273}
1274
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001275void CGOpenMPRuntime::emitForFinish(CodeGenFunction &CGF, SourceLocation Loc,
1276 OpenMPScheduleClauseKind ScheduleKind) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001277 assert((ScheduleKind == OMPC_SCHEDULE_static ||
1278 ScheduleKind == OMPC_SCHEDULE_unknown) &&
1279 "Non-static schedule kinds are not yet implemented");
1280 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001281 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1282 getThreadID(CGF, Loc)};
1283 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1284 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001285}
1286
Alexander Musman92bdaab2015-03-12 13:37:50 +00001287llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1288 SourceLocation Loc, unsigned IVSize,
1289 bool IVSigned, llvm::Value *IL,
1290 llvm::Value *LB, llvm::Value *UB,
1291 llvm::Value *ST) {
1292 // Call __kmpc_dispatch_next(
1293 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1294 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1295 // kmp_int[32|64] *p_stride);
1296 llvm::Value *Args[] = {
1297 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1298 IL, // &isLastIter
1299 LB, // &Lower
1300 UB, // &Upper
1301 ST // &Stride
1302 };
1303 llvm::Value *Call =
1304 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1305 return CGF.EmitScalarConversion(
1306 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1307 CGF.getContext().BoolTy);
1308}
1309
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001310void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1311 llvm::Value *NumThreads,
1312 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001313 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1314 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001315 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001316 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001317 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1318 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001319}
1320
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001321void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1322 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001323 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001324 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1325 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001326}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001327
Alexey Bataev62b63b12015-03-10 07:28:44 +00001328namespace {
1329/// \brief Indexes of fields for type kmp_task_t.
1330enum KmpTaskTFields {
1331 /// \brief List of shared variables.
1332 KmpTaskTShareds,
1333 /// \brief Task routine.
1334 KmpTaskTRoutine,
1335 /// \brief Partition id for the untied tasks.
1336 KmpTaskTPartId,
1337 /// \brief Function with call of destructors for private variables.
1338 KmpTaskTDestructors,
1339};
1340} // namespace
1341
1342void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1343 if (!KmpRoutineEntryPtrTy) {
1344 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1345 auto &C = CGM.getContext();
1346 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1347 FunctionProtoType::ExtProtoInfo EPI;
1348 KmpRoutineEntryPtrQTy = C.getPointerType(
1349 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1350 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1351 }
1352}
1353
1354static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1355 QualType FieldTy) {
1356 auto *Field = FieldDecl::Create(
1357 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1358 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1359 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1360 Field->setAccess(AS_public);
1361 DC->addDecl(Field);
1362}
1363
1364static QualType createKmpTaskTRecordDecl(CodeGenModule &CGM,
1365 QualType KmpInt32Ty,
1366 QualType KmpRoutineEntryPointerQTy) {
1367 auto &C = CGM.getContext();
1368 // Build struct kmp_task_t {
1369 // void * shareds;
1370 // kmp_routine_entry_t routine;
1371 // kmp_int32 part_id;
1372 // kmp_routine_entry_t destructors;
1373 // /* private vars */
1374 // };
1375 auto *RD = C.buildImplicitRecord("kmp_task_t");
1376 RD->startDefinition();
1377 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1378 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1379 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1380 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1381 // TODO: add private fields.
1382 RD->completeDefinition();
1383 return C.getRecordType(RD);
1384}
1385
1386/// \brief Emit a proxy function which accepts kmp_task_t as the second
1387/// argument.
1388/// \code
1389/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1390/// TaskFunction(gtid, tt->part_id, tt->shareds);
1391/// return 0;
1392/// }
1393/// \endcode
1394static llvm::Value *
1395emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
1396 QualType KmpInt32Ty, QualType KmpTaskTPtrQTy,
David Blaikie1ed728c2015-04-05 22:45:47 +00001397 QualType SharedsPtrTy, llvm::Value *TaskFunction, llvm::Type *KmpTaskTTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001398 auto &C = CGM.getContext();
1399 FunctionArgList Args;
1400 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1401 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
1402 /*Id=*/nullptr, KmpTaskTPtrQTy);
1403 Args.push_back(&GtidArg);
1404 Args.push_back(&TaskTypeArg);
1405 FunctionType::ExtInfo Info;
1406 auto &TaskEntryFnInfo =
1407 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1408 /*isVariadic=*/false);
1409 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1410 auto *TaskEntry =
1411 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1412 ".omp_task_entry.", &CGM.getModule());
1413 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1414 CodeGenFunction CGF(CGM);
1415 CGF.disableDebugInfo();
1416 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1417
1418 // TaskFunction(gtid, tt->part_id, tt->shareds);
1419 auto *GtidParam = CGF.EmitLoadOfScalar(
1420 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1421 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1422 auto TaskTypeArgAddr = CGF.EmitLoadOfScalar(
1423 CGF.GetAddrOfLocalVar(&TaskTypeArg), /*Volatile=*/false,
1424 CGM.PointerAlignInBytes, KmpTaskTPtrQTy, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001425 auto *PartidPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001426 /*Idx=*/KmpTaskTPartId);
1427 auto *PartidParam = CGF.EmitLoadOfScalar(
1428 PartidPtr, /*Volatile=*/false,
1429 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001430 auto *SharedsPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001431 /*Idx=*/KmpTaskTShareds);
1432 auto *SharedsParam =
1433 CGF.EmitLoadOfScalar(SharedsPtr, /*Volatile=*/false,
1434 CGM.PointerAlignInBytes, C.VoidPtrTy, Loc);
1435 llvm::Value *CallArgs[] = {
1436 GtidParam, PartidParam,
1437 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1438 SharedsParam, CGF.ConvertTypeForMem(SharedsPtrTy))};
1439 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1440 CGF.EmitStoreThroughLValue(
1441 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1442 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1443 CGF.FinishFunction();
1444 return TaskEntry;
1445}
1446
1447void CGOpenMPRuntime::emitTaskCall(
1448 CodeGenFunction &CGF, SourceLocation Loc, bool Tied,
1449 llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
1450 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds) {
1451 auto &C = CGM.getContext();
1452 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1453 // Build type kmp_routine_entry_t (if not built yet).
1454 emitKmpRoutineEntryT(KmpInt32Ty);
1455 // Build particular struct kmp_task_t for the given task.
1456 auto KmpTaskQTy =
1457 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy);
1458 QualType KmpTaskTPtrQTy = C.getPointerType(KmpTaskQTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00001459 auto *KmpTaskTTy = CGF.ConvertType(KmpTaskQTy);
1460 auto *KmpTaskTPtrTy = KmpTaskTTy->getPointerTo();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001461 auto KmpTaskTySize = CGM.getSize(C.getTypeSizeInChars(KmpTaskQTy));
1462 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
1463
1464 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
1465 // kmp_task_t *tt);
David Blaikie1ed728c2015-04-05 22:45:47 +00001466 auto *TaskEntry =
1467 emitProxyTaskFunction(CGM, Loc, KmpInt32Ty, KmpTaskTPtrQTy, SharedsPtrTy,
1468 TaskFunction, KmpTaskTTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001469
1470 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1471 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1472 // kmp_routine_entry_t *task_entry);
1473 // Task flags. Format is taken from
1474 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
1475 // description of kmp_tasking_flags struct.
1476 const unsigned TiedFlag = 0x1;
1477 const unsigned FinalFlag = 0x2;
1478 unsigned Flags = Tied ? TiedFlag : 0;
1479 auto *TaskFlags =
1480 Final.getPointer()
1481 ? CGF.Builder.CreateSelect(Final.getPointer(),
1482 CGF.Builder.getInt32(FinalFlag),
1483 CGF.Builder.getInt32(/*C=*/0))
1484 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
1485 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
1486 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
1487 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
1488 getThreadID(CGF, Loc), TaskFlags, KmpTaskTySize,
1489 CGM.getSize(SharedsSize),
1490 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1491 TaskEntry, KmpRoutineEntryPtrTy)};
1492 auto *NewTask = CGF.EmitRuntimeCall(
1493 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
1494 auto *NewTaskNewTaskTTy =
1495 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NewTask, KmpTaskTPtrTy);
1496 // Fill the data in the resulting kmp_task_t record.
1497 // Copy shareds if there are any.
1498 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty())
1499 CGF.EmitAggregateCopy(
1500 CGF.EmitLoadOfScalar(
David Blaikie1ed728c2015-04-05 22:45:47 +00001501 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001502 /*Idx=*/KmpTaskTShareds),
1503 /*Volatile=*/false, CGM.PointerAlignInBytes, SharedsPtrTy, Loc),
1504 Shareds, SharedsTy);
1505 // TODO: generate function with destructors for privates.
1506 // Provide pointer to function with destructors for privates.
1507 CGF.Builder.CreateAlignedStore(
1508 llvm::ConstantPointerNull::get(
1509 cast<llvm::PointerType>(KmpRoutineEntryPtrTy)),
David Blaikie1ed728c2015-04-05 22:45:47 +00001510 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001511 /*Idx=*/KmpTaskTDestructors),
1512 CGM.PointerAlignInBytes);
1513
1514 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
1515 // libcall.
1516 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1517 // *new_task);
1518 llvm::Value *TaskArgs[] = {emitUpdateLocation(CGF, Loc),
1519 getThreadID(CGF, Loc), NewTask};
1520 // TODO: add check for untied tasks.
1521 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1522}
1523
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001524InlinedOpenMPRegionRAII::InlinedOpenMPRegionRAII(
1525 CodeGenFunction &CGF, const OMPExecutableDirective &D)
1526 : CGF(CGF) {
1527 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(D, CGF.CapturedStmtInfo);
Alexey Bataev36bf0112015-03-10 05:15:26 +00001528 // 1.2.2 OpenMP Language Terminology
1529 // Structured block - An executable statement with a single entry at the
1530 // top and a single exit at the bottom.
1531 // The point of exit cannot be a branch out of the structured block.
1532 // longjmp() and throw() must not violate the entry/exit criteria.
1533 CGF.EHStack.pushTerminate();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001534}
1535
1536InlinedOpenMPRegionRAII::~InlinedOpenMPRegionRAII() {
Alexey Bataev36bf0112015-03-10 05:15:26 +00001537 CGF.EHStack.popTerminate();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001538 auto *OldCSI =
1539 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
1540 delete CGF.CapturedStmtInfo;
1541 CGF.CapturedStmtInfo = OldCSI;
1542}
1543