blob: 2dbaae5624c771b2f48ad80e933fe13d896c6064 [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;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000306 auto *PSource =
Alexey Bataev9959db52014-05-06 10:08:46 +0000307 CGF.Builder.CreateConstInBoundsGEP2_32(LocValue, 0, IdentField_PSource);
308
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(
1024 CGF.Builder.CreateAlignedLoad(CGF.Builder.CreateStructGEP(RHS, I),
1025 CGM.PointerAlignInBytes),
1026 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1027 });
1028 Scope.addPrivate(
1029 cast<VarDecl>(cast<DeclRefExpr>(DstExprs[I])->getDecl()),
1030 [&]() -> llvm::Value *{
1031 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1032 CGF.Builder.CreateAlignedLoad(CGF.Builder.CreateStructGEP(LHS, I),
1033 CGM.PointerAlignInBytes),
1034 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1035 });
1036 }
1037 Scope.Privatize();
1038 for (auto *E : AssignmentOps) {
1039 CGF.EmitIgnoredExpr(E);
1040 }
1041 Scope.ForceCleanup();
1042 CGF.FinishFunction();
1043 return Fn;
1044}
1045
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001046void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
1047 const std::function<void()> &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001048 SourceLocation Loc,
1049 ArrayRef<const Expr *> CopyprivateVars,
1050 ArrayRef<const Expr *> SrcExprs,
1051 ArrayRef<const Expr *> DstExprs,
1052 ArrayRef<const Expr *> AssignmentOps) {
1053 assert(CopyprivateVars.size() == SrcExprs.size() &&
1054 CopyprivateVars.size() == DstExprs.size() &&
1055 CopyprivateVars.size() == AssignmentOps.size());
1056 auto &C = CGM.getContext();
1057 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001058 // if(__kmpc_single(ident_t *, gtid)) {
1059 // SingleOpGen();
1060 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001061 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001062 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001063 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1064 // <copy_func>, did_it);
1065
1066 llvm::AllocaInst *DidIt = nullptr;
1067 if (!CopyprivateVars.empty()) {
1068 // int32 did_it = 0;
1069 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1070 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
1071 CGF.InitTempAlloca(DidIt, CGF.Builder.getInt32(0));
1072 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001073 // Prepare arguments and build a call to __kmpc_single
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001074 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1075 auto *IsSingle =
1076 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
1077 emitIfStmt(CGF, IsSingle, [&]() -> void {
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001078 SingleOpGen();
Alexey Bataeva63048e2015-03-23 06:18:07 +00001079 if (DidIt) {
1080 // did_it = 1;
1081 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1082 DidIt->getAlignment());
1083 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001084 // Build a call to __kmpc_end_single.
1085 // OpenMP [1.2.2 OpenMP Language Terminology]
1086 // For C/C++, an executable statement, possibly compound, with a single
1087 // entry at the top and a single exit at the bottom, or an OpenMP construct.
1088 // * Access to the structured block must not be the result of a branch.
1089 // * The point of exit cannot be a branch out of the structured block.
1090 // * The point of entry must not be a call to setjmp().
1091 // * longjmp() and throw() must not violate the entry/exit criteria.
1092 // * An expression statement, iteration statement, selection statement, or
1093 // try block is considered to be a structured block if the corresponding
1094 // compound statement obtained by enclosing it in { and } would be a
1095 // structured block.
1096 // It is analyzed in Sema, so we can just call __kmpc_end_single() on
1097 // fallthrough rather than pushing a normal cleanup for it.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001098 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_single), Args);
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001099 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001100 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1101 // <copy_func>, did_it);
1102 if (DidIt) {
1103 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1104 auto CopyprivateArrayTy =
1105 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1106 /*IndexTypeQuals=*/0);
1107 // Create a list of all private variables for copyprivate.
1108 auto *CopyprivateList =
1109 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1110 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
1111 auto *Elem = CGF.Builder.CreateStructGEP(CopyprivateList, I);
1112 CGF.Builder.CreateAlignedStore(
1113 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1114 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1115 Elem, CGM.PointerAlignInBytes);
1116 }
1117 // Build function that copies private values from single region to all other
1118 // threads in the corresponding parallel region.
1119 auto *CpyFn = emitCopyprivateCopyFunction(
1120 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
1121 SrcExprs, DstExprs, AssignmentOps);
1122 auto *BufSize = CGF.Builder.getInt32(
1123 C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
1124 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1125 CGF.VoidPtrTy);
1126 auto *DidItVal =
1127 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1128 llvm::Value *Args[] = {
1129 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1130 getThreadID(CGF, Loc), // i32 <gtid>
1131 BufSize, // i32 <buf_size>
1132 CL, // void *<copyprivate list>
1133 CpyFn, // void (*) (void *, void *) <copy_func>
1134 DidItVal // i32 did_it
1135 };
1136 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1137 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001138}
1139
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001140void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf2685682015-03-30 04:30:22 +00001141 OpenMPDirectiveKind Kind) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001142 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001143 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1144 if (Kind == OMPD_for) {
1145 Flags =
1146 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1147 } else if (Kind == OMPD_sections) {
1148 Flags = static_cast<OpenMPLocationFlags>(Flags |
1149 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1150 } else if (Kind == OMPD_single) {
1151 Flags =
1152 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1153 } else if (Kind == OMPD_barrier) {
1154 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1155 } else {
1156 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1157 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001158 // Build call __kmpc_cancel_barrier(loc, thread_id);
1159 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1160 // one provides the same functionality and adds initial support for
1161 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1162 // is provided default by the runtime library so it safe to make such
1163 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001164 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1165 getThreadID(CGF, Loc)};
1166 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001167}
1168
Alexander Musmanc6388682014-12-15 07:07:06 +00001169/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1170/// the enum sched_type in kmp.h).
1171enum OpenMPSchedType {
1172 /// \brief Lower bound for default (unordered) versions.
1173 OMP_sch_lower = 32,
1174 OMP_sch_static_chunked = 33,
1175 OMP_sch_static = 34,
1176 OMP_sch_dynamic_chunked = 35,
1177 OMP_sch_guided_chunked = 36,
1178 OMP_sch_runtime = 37,
1179 OMP_sch_auto = 38,
1180 /// \brief Lower bound for 'ordered' versions.
1181 OMP_ord_lower = 64,
1182 /// \brief Lower bound for 'nomerge' versions.
1183 OMP_nm_lower = 160,
1184};
1185
1186/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1187static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
1188 bool Chunked) {
1189 switch (ScheduleKind) {
1190 case OMPC_SCHEDULE_static:
1191 return Chunked ? OMP_sch_static_chunked : OMP_sch_static;
1192 case OMPC_SCHEDULE_dynamic:
1193 return OMP_sch_dynamic_chunked;
1194 case OMPC_SCHEDULE_guided:
1195 return OMP_sch_guided_chunked;
1196 case OMPC_SCHEDULE_auto:
1197 return OMP_sch_auto;
1198 case OMPC_SCHEDULE_runtime:
1199 return OMP_sch_runtime;
1200 case OMPC_SCHEDULE_unknown:
1201 assert(!Chunked && "chunk was specified but schedule kind not known");
1202 return OMP_sch_static;
1203 }
1204 llvm_unreachable("Unexpected runtime schedule");
1205}
1206
1207bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1208 bool Chunked) const {
1209 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
1210 return Schedule == OMP_sch_static;
1211}
1212
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001213bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
1214 auto Schedule = getRuntimeSchedule(ScheduleKind, /* Chunked */ false);
1215 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1216 return Schedule != OMP_sch_static;
1217}
1218
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001219void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1220 OpenMPScheduleClauseKind ScheduleKind,
1221 unsigned IVSize, bool IVSigned,
1222 llvm::Value *IL, llvm::Value *LB,
1223 llvm::Value *UB, llvm::Value *ST,
1224 llvm::Value *Chunk) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001225 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunk != nullptr);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001226 if (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked) {
1227 // Call __kmpc_dispatch_init(
1228 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1229 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1230 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001231
Alexander Musman92bdaab2015-03-12 13:37:50 +00001232 // If the Chunk was not specified in the clause - use default value 1.
1233 if (Chunk == nullptr)
1234 Chunk = CGF.Builder.getIntN(IVSize, 1);
1235 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1236 getThreadID(CGF, Loc),
1237 CGF.Builder.getInt32(Schedule), // Schedule type
1238 CGF.Builder.getIntN(IVSize, 0), // Lower
1239 UB, // Upper
1240 CGF.Builder.getIntN(IVSize, 1), // Stride
1241 Chunk // Chunk
1242 };
1243 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1244 } else {
1245 // Call __kmpc_for_static_init(
1246 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1247 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1248 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1249 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1250 if (Chunk == nullptr) {
1251 assert(Schedule == OMP_sch_static &&
1252 "expected static non-chunked schedule");
1253 // If the Chunk was not specified in the clause - use default value 1.
1254 Chunk = CGF.Builder.getIntN(IVSize, 1);
1255 } else
1256 assert(Schedule == OMP_sch_static_chunked &&
1257 "expected static chunked schedule");
1258 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1259 getThreadID(CGF, Loc),
1260 CGF.Builder.getInt32(Schedule), // Schedule type
1261 IL, // &isLastIter
1262 LB, // &LB
1263 UB, // &UB
1264 ST, // &Stride
1265 CGF.Builder.getIntN(IVSize, 1), // Incr
1266 Chunk // Chunk
1267 };
Alexander Musman21212e42015-03-13 10:38:23 +00001268 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001269 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001270}
1271
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001272void CGOpenMPRuntime::emitForFinish(CodeGenFunction &CGF, SourceLocation Loc,
1273 OpenMPScheduleClauseKind ScheduleKind) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001274 assert((ScheduleKind == OMPC_SCHEDULE_static ||
1275 ScheduleKind == OMPC_SCHEDULE_unknown) &&
1276 "Non-static schedule kinds are not yet implemented");
1277 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001278 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1279 getThreadID(CGF, Loc)};
1280 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1281 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001282}
1283
Alexander Musman92bdaab2015-03-12 13:37:50 +00001284llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1285 SourceLocation Loc, unsigned IVSize,
1286 bool IVSigned, llvm::Value *IL,
1287 llvm::Value *LB, llvm::Value *UB,
1288 llvm::Value *ST) {
1289 // Call __kmpc_dispatch_next(
1290 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1291 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1292 // kmp_int[32|64] *p_stride);
1293 llvm::Value *Args[] = {
1294 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1295 IL, // &isLastIter
1296 LB, // &Lower
1297 UB, // &Upper
1298 ST // &Stride
1299 };
1300 llvm::Value *Call =
1301 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1302 return CGF.EmitScalarConversion(
1303 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1304 CGF.getContext().BoolTy);
1305}
1306
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001307void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1308 llvm::Value *NumThreads,
1309 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001310 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1311 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001312 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001313 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001314 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1315 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001316}
1317
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001318void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1319 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001320 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001321 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1322 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001323}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001324
Alexey Bataev62b63b12015-03-10 07:28:44 +00001325namespace {
1326/// \brief Indexes of fields for type kmp_task_t.
1327enum KmpTaskTFields {
1328 /// \brief List of shared variables.
1329 KmpTaskTShareds,
1330 /// \brief Task routine.
1331 KmpTaskTRoutine,
1332 /// \brief Partition id for the untied tasks.
1333 KmpTaskTPartId,
1334 /// \brief Function with call of destructors for private variables.
1335 KmpTaskTDestructors,
1336};
1337} // namespace
1338
1339void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1340 if (!KmpRoutineEntryPtrTy) {
1341 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1342 auto &C = CGM.getContext();
1343 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1344 FunctionProtoType::ExtProtoInfo EPI;
1345 KmpRoutineEntryPtrQTy = C.getPointerType(
1346 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1347 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1348 }
1349}
1350
1351static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1352 QualType FieldTy) {
1353 auto *Field = FieldDecl::Create(
1354 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1355 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1356 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1357 Field->setAccess(AS_public);
1358 DC->addDecl(Field);
1359}
1360
1361static QualType createKmpTaskTRecordDecl(CodeGenModule &CGM,
1362 QualType KmpInt32Ty,
1363 QualType KmpRoutineEntryPointerQTy) {
1364 auto &C = CGM.getContext();
1365 // Build struct kmp_task_t {
1366 // void * shareds;
1367 // kmp_routine_entry_t routine;
1368 // kmp_int32 part_id;
1369 // kmp_routine_entry_t destructors;
1370 // /* private vars */
1371 // };
1372 auto *RD = C.buildImplicitRecord("kmp_task_t");
1373 RD->startDefinition();
1374 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1375 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1376 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1377 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1378 // TODO: add private fields.
1379 RD->completeDefinition();
1380 return C.getRecordType(RD);
1381}
1382
1383/// \brief Emit a proxy function which accepts kmp_task_t as the second
1384/// argument.
1385/// \code
1386/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1387/// TaskFunction(gtid, tt->part_id, tt->shareds);
1388/// return 0;
1389/// }
1390/// \endcode
1391static llvm::Value *
1392emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
1393 QualType KmpInt32Ty, QualType KmpTaskTPtrQTy,
1394 QualType SharedsPtrTy, llvm::Value *TaskFunction) {
1395 auto &C = CGM.getContext();
1396 FunctionArgList Args;
1397 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1398 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
1399 /*Id=*/nullptr, KmpTaskTPtrQTy);
1400 Args.push_back(&GtidArg);
1401 Args.push_back(&TaskTypeArg);
1402 FunctionType::ExtInfo Info;
1403 auto &TaskEntryFnInfo =
1404 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1405 /*isVariadic=*/false);
1406 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1407 auto *TaskEntry =
1408 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1409 ".omp_task_entry.", &CGM.getModule());
1410 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1411 CodeGenFunction CGF(CGM);
1412 CGF.disableDebugInfo();
1413 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1414
1415 // TaskFunction(gtid, tt->part_id, tt->shareds);
1416 auto *GtidParam = CGF.EmitLoadOfScalar(
1417 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1418 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1419 auto TaskTypeArgAddr = CGF.EmitLoadOfScalar(
1420 CGF.GetAddrOfLocalVar(&TaskTypeArg), /*Volatile=*/false,
1421 CGM.PointerAlignInBytes, KmpTaskTPtrQTy, Loc);
1422 auto *PartidPtr = CGF.Builder.CreateStructGEP(TaskTypeArgAddr,
1423 /*Idx=*/KmpTaskTPartId);
1424 auto *PartidParam = CGF.EmitLoadOfScalar(
1425 PartidPtr, /*Volatile=*/false,
1426 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1427 auto *SharedsPtr = CGF.Builder.CreateStructGEP(TaskTypeArgAddr,
1428 /*Idx=*/KmpTaskTShareds);
1429 auto *SharedsParam =
1430 CGF.EmitLoadOfScalar(SharedsPtr, /*Volatile=*/false,
1431 CGM.PointerAlignInBytes, C.VoidPtrTy, Loc);
1432 llvm::Value *CallArgs[] = {
1433 GtidParam, PartidParam,
1434 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1435 SharedsParam, CGF.ConvertTypeForMem(SharedsPtrTy))};
1436 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1437 CGF.EmitStoreThroughLValue(
1438 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1439 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1440 CGF.FinishFunction();
1441 return TaskEntry;
1442}
1443
1444void CGOpenMPRuntime::emitTaskCall(
1445 CodeGenFunction &CGF, SourceLocation Loc, bool Tied,
1446 llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
1447 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds) {
1448 auto &C = CGM.getContext();
1449 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1450 // Build type kmp_routine_entry_t (if not built yet).
1451 emitKmpRoutineEntryT(KmpInt32Ty);
1452 // Build particular struct kmp_task_t for the given task.
1453 auto KmpTaskQTy =
1454 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy);
1455 QualType KmpTaskTPtrQTy = C.getPointerType(KmpTaskQTy);
1456 auto KmpTaskTPtrTy = CGF.ConvertType(KmpTaskQTy)->getPointerTo();
1457 auto KmpTaskTySize = CGM.getSize(C.getTypeSizeInChars(KmpTaskQTy));
1458 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
1459
1460 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
1461 // kmp_task_t *tt);
1462 auto *TaskEntry = emitProxyTaskFunction(CGM, Loc, KmpInt32Ty, KmpTaskTPtrQTy,
1463 SharedsPtrTy, TaskFunction);
1464
1465 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1466 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1467 // kmp_routine_entry_t *task_entry);
1468 // Task flags. Format is taken from
1469 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
1470 // description of kmp_tasking_flags struct.
1471 const unsigned TiedFlag = 0x1;
1472 const unsigned FinalFlag = 0x2;
1473 unsigned Flags = Tied ? TiedFlag : 0;
1474 auto *TaskFlags =
1475 Final.getPointer()
1476 ? CGF.Builder.CreateSelect(Final.getPointer(),
1477 CGF.Builder.getInt32(FinalFlag),
1478 CGF.Builder.getInt32(/*C=*/0))
1479 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
1480 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
1481 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
1482 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
1483 getThreadID(CGF, Loc), TaskFlags, KmpTaskTySize,
1484 CGM.getSize(SharedsSize),
1485 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1486 TaskEntry, KmpRoutineEntryPtrTy)};
1487 auto *NewTask = CGF.EmitRuntimeCall(
1488 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
1489 auto *NewTaskNewTaskTTy =
1490 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NewTask, KmpTaskTPtrTy);
1491 // Fill the data in the resulting kmp_task_t record.
1492 // Copy shareds if there are any.
1493 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty())
1494 CGF.EmitAggregateCopy(
1495 CGF.EmitLoadOfScalar(
1496 CGF.Builder.CreateStructGEP(NewTaskNewTaskTTy,
1497 /*Idx=*/KmpTaskTShareds),
1498 /*Volatile=*/false, CGM.PointerAlignInBytes, SharedsPtrTy, Loc),
1499 Shareds, SharedsTy);
1500 // TODO: generate function with destructors for privates.
1501 // Provide pointer to function with destructors for privates.
1502 CGF.Builder.CreateAlignedStore(
1503 llvm::ConstantPointerNull::get(
1504 cast<llvm::PointerType>(KmpRoutineEntryPtrTy)),
1505 CGF.Builder.CreateStructGEP(NewTaskNewTaskTTy,
1506 /*Idx=*/KmpTaskTDestructors),
1507 CGM.PointerAlignInBytes);
1508
1509 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
1510 // libcall.
1511 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1512 // *new_task);
1513 llvm::Value *TaskArgs[] = {emitUpdateLocation(CGF, Loc),
1514 getThreadID(CGF, Loc), NewTask};
1515 // TODO: add check for untied tasks.
1516 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1517}
1518
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001519InlinedOpenMPRegionRAII::InlinedOpenMPRegionRAII(
1520 CodeGenFunction &CGF, const OMPExecutableDirective &D)
1521 : CGF(CGF) {
1522 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(D, CGF.CapturedStmtInfo);
Alexey Bataev36bf0112015-03-10 05:15:26 +00001523 // 1.2.2 OpenMP Language Terminology
1524 // Structured block - An executable statement with a single entry at the
1525 // top and a single exit at the bottom.
1526 // The point of exit cannot be a branch out of the structured block.
1527 // longjmp() and throw() must not violate the entry/exit criteria.
1528 CGF.EHStack.pushTerminate();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001529}
1530
1531InlinedOpenMPRegionRAII::~InlinedOpenMPRegionRAII() {
Alexey Bataev36bf0112015-03-10 05:15:26 +00001532 CGF.EHStack.popTerminate();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001533 auto *OldCSI =
1534 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
1535 delete CGF.CapturedStmtInfo;
1536 CGF.CapturedStmtInfo = OldCSI;
1537}
1538