blob: 9d33b16fab74d822e12767ad7180c315c57e8604 [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(),
182 /*IsExplicit=*/false);
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
214llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000215CGOpenMPRuntime::emitOutlinedFunction(const OMPExecutableDirective &D,
216 const VarDecl *ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217 assert(ThreadIDVar->getType()->isPointerType() &&
218 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000219 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
220 CodeGenFunction CGF(CGM, true);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000221 CGOpenMPOutlinedRegionInfo CGInfo(D, *CS, ThreadIDVar);
Alexey Bataev18095712014-10-10 12:19:54 +0000222 CGF.CapturedStmtInfo = &CGInfo;
223 return CGF.GenerateCapturedStmtFunction(*CS);
224}
225
226llvm::Value *
Alexey Bataev62b63b12015-03-10 07:28:44 +0000227CGOpenMPRuntime::emitTaskOutlinedFunction(const OMPExecutableDirective &D,
228 const VarDecl *ThreadIDVar,
229 const VarDecl *PartIDVar) {
230 assert(!ThreadIDVar->getType()->isPointerType() &&
231 "thread id variable must be of type kmp_int32 for tasks");
232 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
233 CodeGenFunction CGF(CGM, true);
234 CGOpenMPTaskOutlinedRegionInfo CGInfo(D, *CS, ThreadIDVar, PartIDVar);
235 CGF.CapturedStmtInfo = &CGInfo;
236 return CGF.GenerateCapturedStmtFunction(*CS);
237}
238
239llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000240CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000241 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000242 if (!Entry) {
243 if (!DefaultOpenMPPSource) {
244 // Initialize default location for psource field of ident_t structure of
245 // all ident_t objects. Format is ";file;function;line;column;;".
246 // Taken from
247 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
248 DefaultOpenMPPSource =
249 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
250 DefaultOpenMPPSource =
251 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
252 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000253 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
254 CGM.getModule(), IdentTy, /*isConstant*/ true,
255 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000256 DefaultOpenMPLocation->setUnnamedAddr(true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000257
258 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000259 llvm::Constant *Values[] = {Zero,
260 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
261 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000262 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
263 DefaultOpenMPLocation->setInitializer(Init);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000264 OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000265 return DefaultOpenMPLocation;
266 }
267 return Entry;
268}
269
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000270llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
271 SourceLocation Loc,
272 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000273 // If no debug info is generated - return global default location.
274 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
275 Loc.isInvalid())
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000276 return getOrCreateDefaultLocation(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000277
278 assert(CGF.CurFn && "No function in current CodeGenFunction.");
279
Alexey Bataev9959db52014-05-06 10:08:46 +0000280 llvm::Value *LocValue = nullptr;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000281 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
282 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataev18095712014-10-10 12:19:54 +0000283 LocValue = I->second.DebugLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +0000284 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
285 // GetOpenMPThreadID was called before this routine.
286 if (LocValue == nullptr) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000287 // Generate "ident_t .kmpc_loc.addr;"
288 llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
Alexey Bataev9959db52014-05-06 10:08:46 +0000289 AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
Alexey Bataev18095712014-10-10 12:19:54 +0000290 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
291 Elem.second.DebugLoc = AI;
Alexey Bataev9959db52014-05-06 10:08:46 +0000292 LocValue = AI;
293
294 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
295 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000296 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataev9959db52014-05-06 10:08:46 +0000297 llvm::ConstantExpr::getSizeOf(IdentTy),
298 CGM.PointerAlignInBytes);
299 }
300
301 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000302 auto *PSource =
Alexey Bataev9959db52014-05-06 10:08:46 +0000303 CGF.Builder.CreateConstInBoundsGEP2_32(LocValue, 0, IdentField_PSource);
304
Alexey Bataevf002aca2014-05-30 05:48:40 +0000305 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
306 if (OMPDebugLoc == nullptr) {
307 SmallString<128> Buffer2;
308 llvm::raw_svector_ostream OS2(Buffer2);
309 // Build debug location
310 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
311 OS2 << ";" << PLoc.getFilename() << ";";
312 if (const FunctionDecl *FD =
313 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
314 OS2 << FD->getQualifiedNameAsString();
315 }
316 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
317 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
318 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000319 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000320 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000321 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
322
Alexey Bataev9959db52014-05-06 10:08:46 +0000323 return LocValue;
324}
325
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000326llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
327 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000328 assert(CGF.CurFn && "No function in current CodeGenFunction.");
329
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000330 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000331 // Check whether we've already cached a load of the thread id in this
332 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000333 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000334 if (I != OpenMPLocThreadIDMap.end()) {
335 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000336 if (ThreadID != nullptr)
337 return ThreadID;
338 }
339 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000340 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000341 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000342 // Check if this an outlined function with thread id passed as argument.
343 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000344 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
345 // If value loaded in entry block, cache it and use it everywhere in
346 // function.
347 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
348 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
349 Elem.second.ThreadID = ThreadID;
350 }
351 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000352 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000353 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000354
355 // This is not an outlined function region - need to call __kmpc_int32
356 // kmpc_global_thread_num(ident_t *loc).
357 // Generate thread id value and cache this value for use across the
358 // function.
359 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
360 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
361 ThreadID =
362 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
363 emitUpdateLocation(CGF, Loc));
364 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
365 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000366 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000367}
368
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000369void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000370 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000371 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
372 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000373}
374
375llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
376 return llvm::PointerType::getUnqual(IdentTy);
377}
378
379llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
380 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
381}
382
383llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000384CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000385 llvm::Constant *RTLFn = nullptr;
386 switch (Function) {
387 case OMPRTL__kmpc_fork_call: {
388 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
389 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000390 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
391 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000392 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000393 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000394 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
395 break;
396 }
397 case OMPRTL__kmpc_global_thread_num: {
398 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000399 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000400 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000401 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000402 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
403 break;
404 }
Alexey Bataev97720002014-11-11 04:05:39 +0000405 case OMPRTL__kmpc_threadprivate_cached: {
406 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
407 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
408 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
409 CGM.VoidPtrTy, CGM.SizeTy,
410 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
411 llvm::FunctionType *FnTy =
412 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
413 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
414 break;
415 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000416 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000417 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
418 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000419 llvm::Type *TypeParams[] = {
420 getIdentTyPointerTy(), CGM.Int32Ty,
421 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
422 llvm::FunctionType *FnTy =
423 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
424 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
425 break;
426 }
Alexey Bataev97720002014-11-11 04:05:39 +0000427 case OMPRTL__kmpc_threadprivate_register: {
428 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
429 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
430 // typedef void *(*kmpc_ctor)(void *);
431 auto KmpcCtorTy =
432 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
433 /*isVarArg*/ false)->getPointerTo();
434 // typedef void *(*kmpc_cctor)(void *, void *);
435 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
436 auto KmpcCopyCtorTy =
437 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
438 /*isVarArg*/ false)->getPointerTo();
439 // typedef void (*kmpc_dtor)(void *);
440 auto KmpcDtorTy =
441 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
442 ->getPointerTo();
443 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
444 KmpcCopyCtorTy, KmpcDtorTy};
445 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
446 /*isVarArg*/ false);
447 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
448 break;
449 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000450 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000451 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
452 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000453 llvm::Type *TypeParams[] = {
454 getIdentTyPointerTy(), CGM.Int32Ty,
455 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
456 llvm::FunctionType *FnTy =
457 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
458 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
459 break;
460 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000461 case OMPRTL__kmpc_cancel_barrier: {
462 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
463 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000464 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
465 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000466 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
467 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000468 break;
469 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000470 case OMPRTL__kmpc_for_static_fini: {
471 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
472 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
473 llvm::FunctionType *FnTy =
474 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
475 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
476 break;
477 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000478 case OMPRTL__kmpc_push_num_threads: {
479 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
480 // kmp_int32 num_threads)
481 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
482 CGM.Int32Ty};
483 llvm::FunctionType *FnTy =
484 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
485 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
486 break;
487 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000488 case OMPRTL__kmpc_serialized_parallel: {
489 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
490 // global_tid);
491 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
492 llvm::FunctionType *FnTy =
493 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
494 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
495 break;
496 }
497 case OMPRTL__kmpc_end_serialized_parallel: {
498 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
499 // global_tid);
500 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
501 llvm::FunctionType *FnTy =
502 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
503 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
504 break;
505 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000506 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000507 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000508 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
509 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000510 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000511 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
512 break;
513 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000514 case OMPRTL__kmpc_master: {
515 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
516 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
517 llvm::FunctionType *FnTy =
518 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
519 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
520 break;
521 }
522 case OMPRTL__kmpc_end_master: {
523 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
524 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
525 llvm::FunctionType *FnTy =
526 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
527 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
528 break;
529 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000530 case OMPRTL__kmpc_omp_taskyield: {
531 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
532 // int end_part);
533 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
534 llvm::FunctionType *FnTy =
535 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
536 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
537 break;
538 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000539 case OMPRTL__kmpc_single: {
540 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
541 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
542 llvm::FunctionType *FnTy =
543 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
544 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
545 break;
546 }
547 case OMPRTL__kmpc_end_single: {
548 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
549 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
550 llvm::FunctionType *FnTy =
551 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
552 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
553 break;
554 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000555 case OMPRTL__kmpc_omp_task_alloc: {
556 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
557 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
558 // kmp_routine_entry_t *task_entry);
559 assert(KmpRoutineEntryPtrTy != nullptr &&
560 "Type kmp_routine_entry_t must be created.");
561 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
562 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
563 // Return void * and then cast to particular kmp_task_t type.
564 llvm::FunctionType *FnTy =
565 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
566 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
567 break;
568 }
569 case OMPRTL__kmpc_omp_task: {
570 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
571 // *new_task);
572 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
573 CGM.VoidPtrTy};
574 llvm::FunctionType *FnTy =
575 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
576 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
577 break;
578 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000579 }
580 return RTLFn;
581}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000582
Alexander Musman21212e42015-03-13 10:38:23 +0000583llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
584 bool IVSigned) {
585 assert((IVSize == 32 || IVSize == 64) &&
586 "IV size is not compatible with the omp runtime");
587 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
588 : "__kmpc_for_static_init_4u")
589 : (IVSigned ? "__kmpc_for_static_init_8"
590 : "__kmpc_for_static_init_8u");
591 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
592 auto PtrTy = llvm::PointerType::getUnqual(ITy);
593 llvm::Type *TypeParams[] = {
594 getIdentTyPointerTy(), // loc
595 CGM.Int32Ty, // tid
596 CGM.Int32Ty, // schedtype
597 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
598 PtrTy, // p_lower
599 PtrTy, // p_upper
600 PtrTy, // p_stride
601 ITy, // incr
602 ITy // chunk
603 };
604 llvm::FunctionType *FnTy =
605 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
606 return CGM.CreateRuntimeFunction(FnTy, Name);
607}
608
Alexander Musman92bdaab2015-03-12 13:37:50 +0000609llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
610 bool IVSigned) {
611 assert((IVSize == 32 || IVSize == 64) &&
612 "IV size is not compatible with the omp runtime");
613 auto Name =
614 IVSize == 32
615 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
616 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
617 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
618 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
619 CGM.Int32Ty, // tid
620 CGM.Int32Ty, // schedtype
621 ITy, // lower
622 ITy, // upper
623 ITy, // stride
624 ITy // chunk
625 };
626 llvm::FunctionType *FnTy =
627 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
628 return CGM.CreateRuntimeFunction(FnTy, Name);
629}
630
631llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
632 bool IVSigned) {
633 assert((IVSize == 32 || IVSize == 64) &&
634 "IV size is not compatible with the omp runtime");
635 auto Name =
636 IVSize == 32
637 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
638 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
639 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
640 auto PtrTy = llvm::PointerType::getUnqual(ITy);
641 llvm::Type *TypeParams[] = {
642 getIdentTyPointerTy(), // loc
643 CGM.Int32Ty, // tid
644 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
645 PtrTy, // p_lower
646 PtrTy, // p_upper
647 PtrTy // p_stride
648 };
649 llvm::FunctionType *FnTy =
650 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
651 return CGM.CreateRuntimeFunction(FnTy, Name);
652}
653
Alexey Bataev97720002014-11-11 04:05:39 +0000654llvm::Constant *
655CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
656 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000657 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000658 Twine(CGM.getMangledName(VD)) + ".cache.");
659}
660
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000661llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
662 const VarDecl *VD,
663 llvm::Value *VDAddr,
664 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000665 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000666 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000667 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
668 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
669 getOrCreateThreadPrivateCache(VD)};
670 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000671 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000672}
673
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000674void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000675 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
676 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
677 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
678 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000679 auto OMPLoc = emitUpdateLocation(CGF, Loc);
680 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000681 OMPLoc);
682 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
683 // to register constructor/destructor for variable.
684 llvm::Value *Args[] = {OMPLoc,
685 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
686 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000687 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000688 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000689}
690
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000691llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000692 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
693 bool PerformInit, CodeGenFunction *CGF) {
694 VD = VD->getDefinition(CGM.getContext());
695 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
696 ThreadPrivateWithDefinition.insert(VD);
697 QualType ASTTy = VD->getType();
698
699 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
700 auto Init = VD->getAnyInitializer();
701 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
702 // Generate function that re-emits the declaration's initializer into the
703 // threadprivate copy of the variable VD
704 CodeGenFunction CtorCGF(CGM);
705 FunctionArgList Args;
706 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
707 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
708 Args.push_back(&Dst);
709
710 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
711 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
712 /*isVariadic=*/false);
713 auto FTy = CGM.getTypes().GetFunctionType(FI);
714 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
715 FTy, ".__kmpc_global_ctor_.", Loc);
716 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
717 Args, SourceLocation());
718 auto ArgVal = CtorCGF.EmitLoadOfScalar(
719 CtorCGF.GetAddrOfLocalVar(&Dst),
720 /*Volatile=*/false, CGM.PointerAlignInBytes,
721 CGM.getContext().VoidPtrTy, Dst.getLocation());
722 auto Arg = CtorCGF.Builder.CreatePointerCast(
723 ArgVal,
724 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
725 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
726 /*IsInitializer=*/true);
727 ArgVal = CtorCGF.EmitLoadOfScalar(
728 CtorCGF.GetAddrOfLocalVar(&Dst),
729 /*Volatile=*/false, CGM.PointerAlignInBytes,
730 CGM.getContext().VoidPtrTy, Dst.getLocation());
731 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
732 CtorCGF.FinishFunction();
733 Ctor = Fn;
734 }
735 if (VD->getType().isDestructedType() != QualType::DK_none) {
736 // Generate function that emits destructor call for the threadprivate copy
737 // of the variable VD
738 CodeGenFunction DtorCGF(CGM);
739 FunctionArgList Args;
740 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
741 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
742 Args.push_back(&Dst);
743
744 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
745 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
746 /*isVariadic=*/false);
747 auto FTy = CGM.getTypes().GetFunctionType(FI);
748 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
749 FTy, ".__kmpc_global_dtor_.", Loc);
750 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
751 SourceLocation());
752 auto ArgVal = DtorCGF.EmitLoadOfScalar(
753 DtorCGF.GetAddrOfLocalVar(&Dst),
754 /*Volatile=*/false, CGM.PointerAlignInBytes,
755 CGM.getContext().VoidPtrTy, Dst.getLocation());
756 DtorCGF.emitDestroy(ArgVal, ASTTy,
757 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
758 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
759 DtorCGF.FinishFunction();
760 Dtor = Fn;
761 }
762 // Do not emit init function if it is not required.
763 if (!Ctor && !Dtor)
764 return nullptr;
765
766 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
767 auto CopyCtorTy =
768 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
769 /*isVarArg=*/false)->getPointerTo();
770 // Copying constructor for the threadprivate variable.
771 // Must be NULL - reserved by runtime, but currently it requires that this
772 // parameter is always NULL. Otherwise it fires assertion.
773 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
774 if (Ctor == nullptr) {
775 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
776 /*isVarArg=*/false)->getPointerTo();
777 Ctor = llvm::Constant::getNullValue(CtorTy);
778 }
779 if (Dtor == nullptr) {
780 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
781 /*isVarArg=*/false)->getPointerTo();
782 Dtor = llvm::Constant::getNullValue(DtorTy);
783 }
784 if (!CGF) {
785 auto InitFunctionTy =
786 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
787 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
788 InitFunctionTy, ".__omp_threadprivate_init_.");
789 CodeGenFunction InitCGF(CGM);
790 FunctionArgList ArgList;
791 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
792 CGM.getTypes().arrangeNullaryFunction(), ArgList,
793 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000794 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000795 InitCGF.FinishFunction();
796 return InitFunction;
797 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000798 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000799 }
800 return nullptr;
801}
802
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000803void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
804 llvm::Value *OutlinedFn,
805 llvm::Value *CapturedStruct) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000806 // Build call __kmpc_fork_call(loc, 1, microtask, captured_struct/*context*/)
807 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000808 emitUpdateLocation(CGF, Loc),
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000809 CGF.Builder.getInt32(1), // Number of arguments after 'microtask' argument
810 // (there is only one additional argument - 'context')
811 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
812 CGF.EmitCastToVoidPtr(CapturedStruct)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000813 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000814 CGF.EmitRuntimeCall(RTLFn, Args);
815}
816
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000817void CGOpenMPRuntime::emitSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
818 llvm::Value *OutlinedFn,
819 llvm::Value *CapturedStruct) {
820 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000821 // Build calls:
822 // __kmpc_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000823 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), ThreadID};
824 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
825 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000826
827 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000828 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000829 auto Int32Ty =
830 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
831 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
832 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
833 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
834 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
835
836 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000837 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
838 CGF.EmitRuntimeCall(
839 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000840}
841
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +0000842// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +0000843// thread-ID variable (it is passed in a first argument of the outlined function
844// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
845// regular serial code region, get thread ID by calling kmp_int32
846// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
847// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000848llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +0000849 SourceLocation Loc) {
850 if (auto OMPRegionInfo =
851 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000852 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +0000853 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000854
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000855 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000856 auto Int32Ty =
857 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
858 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
859 CGF.EmitStoreOfScalar(ThreadID,
860 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
861
862 return ThreadIDTemp;
863}
864
Alexey Bataev97720002014-11-11 04:05:39 +0000865llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000866CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +0000867 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000868 SmallString<256> Buffer;
869 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +0000870 Out << Name;
871 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +0000872 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
873 if (Elem.second) {
874 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +0000875 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +0000876 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +0000877 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000878
David Blaikie13156b62014-11-19 03:06:06 +0000879 return Elem.second = new llvm::GlobalVariable(
880 CGM.getModule(), Ty, /*IsConstant*/ false,
881 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
882 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +0000883}
884
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000885llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +0000886 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000887 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000888}
889
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000890void CGOpenMPRuntime::emitCriticalRegion(
Alexey Bataev75ddfab2014-12-01 11:32:38 +0000891 CodeGenFunction &CGF, StringRef CriticalName,
892 const std::function<void()> &CriticalOpGen, SourceLocation Loc) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000893 auto RegionLock = getCriticalRegionLock(CriticalName);
Alexey Bataev75ddfab2014-12-01 11:32:38 +0000894 // __kmpc_critical(ident_t *, gtid, Lock);
895 // CriticalOpGen();
896 // __kmpc_end_critical(ident_t *, gtid, Lock);
897 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000898 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
899 RegionLock};
900 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev75ddfab2014-12-01 11:32:38 +0000901 CriticalOpGen();
902 // Build a call to __kmpc_end_critical
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000903 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000904}
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000905
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000906static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
907 const std::function<void()> &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +0000908 llvm::Value *CallBool = CGF.EmitScalarConversion(
909 IfCond,
910 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
911 CGF.getContext().BoolTy);
912
913 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
914 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
915 // Generate the branch (If-stmt)
916 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
917 CGF.EmitBlock(ThenBlock);
918 BodyOpGen();
919 // Emit the rest of bblocks/branches
920 CGF.EmitBranch(ContBlock);
921 CGF.EmitBlock(ContBlock, true);
922}
923
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000924void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
925 const std::function<void()> &MasterOpGen,
926 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +0000927 // if(__kmpc_master(ident_t *, gtid)) {
928 // MasterOpGen();
929 // __kmpc_end_master(ident_t *, gtid);
930 // }
931 // Prepare arguments and build a call to __kmpc_master
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000932 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
933 auto *IsMaster =
934 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
935 emitIfStmt(CGF, IsMaster, [&]() -> void {
Alexey Bataev8d690652014-12-04 07:23:53 +0000936 MasterOpGen();
937 // Build a call to __kmpc_end_master.
938 // OpenMP [1.2.2 OpenMP Language Terminology]
939 // For C/C++, an executable statement, possibly compound, with a single
940 // entry at the top and a single exit at the bottom, or an OpenMP construct.
941 // * Access to the structured block must not be the result of a branch.
942 // * The point of exit cannot be a branch out of the structured block.
943 // * The point of entry must not be a call to setjmp().
944 // * longjmp() and throw() must not violate the entry/exit criteria.
945 // * An expression statement, iteration statement, selection statement, or
946 // try block is considered to be a structured block if the corresponding
947 // compound statement obtained by enclosing it in { and } would be a
948 // structured block.
949 // It is analyzed in Sema, so we can just call __kmpc_end_master() on
950 // fallthrough rather than pushing a normal cleanup for it.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000951 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_master), Args);
Alexey Bataev8d690652014-12-04 07:23:53 +0000952 });
953}
954
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000955void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
956 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +0000957 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
958 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000959 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +0000960 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000961 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +0000962}
963
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000964void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
965 const std::function<void()> &SingleOpGen,
966 SourceLocation Loc) {
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000967 // if(__kmpc_single(ident_t *, gtid)) {
968 // SingleOpGen();
969 // __kmpc_end_single(ident_t *, gtid);
970 // }
971 // Prepare arguments and build a call to __kmpc_single
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000972 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
973 auto *IsSingle =
974 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
975 emitIfStmt(CGF, IsSingle, [&]() -> void {
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000976 SingleOpGen();
977 // Build a call to __kmpc_end_single.
978 // OpenMP [1.2.2 OpenMP Language Terminology]
979 // For C/C++, an executable statement, possibly compound, with a single
980 // entry at the top and a single exit at the bottom, or an OpenMP construct.
981 // * Access to the structured block must not be the result of a branch.
982 // * The point of exit cannot be a branch out of the structured block.
983 // * The point of entry must not be a call to setjmp().
984 // * longjmp() and throw() must not violate the entry/exit criteria.
985 // * An expression statement, iteration statement, selection statement, or
986 // try block is considered to be a structured block if the corresponding
987 // compound statement obtained by enclosing it in { and } would be a
988 // structured block.
989 // It is analyzed in Sema, so we can just call __kmpc_end_single() on
990 // fallthrough rather than pushing a normal cleanup for it.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000991 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_end_single), Args);
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000992 });
993}
994
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000995void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
996 bool IsExplicit) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000997 // Build call __kmpc_cancel_barrier(loc, thread_id);
998 auto Flags = static_cast<OpenMPLocationFlags>(
999 OMP_IDENT_KMPC |
1000 (IsExplicit ? OMP_IDENT_BARRIER_EXPL : OMP_IDENT_BARRIER_IMPL));
1001 // Build call __kmpc_cancel_barrier(loc, thread_id);
1002 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1003 // one provides the same functionality and adds initial support for
1004 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1005 // is provided default by the runtime library so it safe to make such
1006 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001007 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1008 getThreadID(CGF, Loc)};
1009 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001010}
1011
Alexander Musmanc6388682014-12-15 07:07:06 +00001012/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1013/// the enum sched_type in kmp.h).
1014enum OpenMPSchedType {
1015 /// \brief Lower bound for default (unordered) versions.
1016 OMP_sch_lower = 32,
1017 OMP_sch_static_chunked = 33,
1018 OMP_sch_static = 34,
1019 OMP_sch_dynamic_chunked = 35,
1020 OMP_sch_guided_chunked = 36,
1021 OMP_sch_runtime = 37,
1022 OMP_sch_auto = 38,
1023 /// \brief Lower bound for 'ordered' versions.
1024 OMP_ord_lower = 64,
1025 /// \brief Lower bound for 'nomerge' versions.
1026 OMP_nm_lower = 160,
1027};
1028
1029/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1030static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
1031 bool Chunked) {
1032 switch (ScheduleKind) {
1033 case OMPC_SCHEDULE_static:
1034 return Chunked ? OMP_sch_static_chunked : OMP_sch_static;
1035 case OMPC_SCHEDULE_dynamic:
1036 return OMP_sch_dynamic_chunked;
1037 case OMPC_SCHEDULE_guided:
1038 return OMP_sch_guided_chunked;
1039 case OMPC_SCHEDULE_auto:
1040 return OMP_sch_auto;
1041 case OMPC_SCHEDULE_runtime:
1042 return OMP_sch_runtime;
1043 case OMPC_SCHEDULE_unknown:
1044 assert(!Chunked && "chunk was specified but schedule kind not known");
1045 return OMP_sch_static;
1046 }
1047 llvm_unreachable("Unexpected runtime schedule");
1048}
1049
1050bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1051 bool Chunked) const {
1052 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
1053 return Schedule == OMP_sch_static;
1054}
1055
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001056bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
1057 auto Schedule = getRuntimeSchedule(ScheduleKind, /* Chunked */ false);
1058 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1059 return Schedule != OMP_sch_static;
1060}
1061
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001062void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1063 OpenMPScheduleClauseKind ScheduleKind,
1064 unsigned IVSize, bool IVSigned,
1065 llvm::Value *IL, llvm::Value *LB,
1066 llvm::Value *UB, llvm::Value *ST,
1067 llvm::Value *Chunk) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001068 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunk != nullptr);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001069 if (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked) {
1070 // Call __kmpc_dispatch_init(
1071 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1072 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1073 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001074
Alexander Musman92bdaab2015-03-12 13:37:50 +00001075 // If the Chunk was not specified in the clause - use default value 1.
1076 if (Chunk == nullptr)
1077 Chunk = CGF.Builder.getIntN(IVSize, 1);
1078 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1079 getThreadID(CGF, Loc),
1080 CGF.Builder.getInt32(Schedule), // Schedule type
1081 CGF.Builder.getIntN(IVSize, 0), // Lower
1082 UB, // Upper
1083 CGF.Builder.getIntN(IVSize, 1), // Stride
1084 Chunk // Chunk
1085 };
1086 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1087 } else {
1088 // Call __kmpc_for_static_init(
1089 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1090 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1091 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1092 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1093 if (Chunk == nullptr) {
1094 assert(Schedule == OMP_sch_static &&
1095 "expected static non-chunked schedule");
1096 // If the Chunk was not specified in the clause - use default value 1.
1097 Chunk = CGF.Builder.getIntN(IVSize, 1);
1098 } else
1099 assert(Schedule == OMP_sch_static_chunked &&
1100 "expected static chunked schedule");
1101 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1102 getThreadID(CGF, Loc),
1103 CGF.Builder.getInt32(Schedule), // Schedule type
1104 IL, // &isLastIter
1105 LB, // &LB
1106 UB, // &UB
1107 ST, // &Stride
1108 CGF.Builder.getIntN(IVSize, 1), // Incr
1109 Chunk // Chunk
1110 };
Alexander Musman21212e42015-03-13 10:38:23 +00001111 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001112 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001113}
1114
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001115void CGOpenMPRuntime::emitForFinish(CodeGenFunction &CGF, SourceLocation Loc,
1116 OpenMPScheduleClauseKind ScheduleKind) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001117 assert((ScheduleKind == OMPC_SCHEDULE_static ||
1118 ScheduleKind == OMPC_SCHEDULE_unknown) &&
1119 "Non-static schedule kinds are not yet implemented");
1120 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001121 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1122 getThreadID(CGF, Loc)};
1123 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1124 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001125}
1126
Alexander Musman92bdaab2015-03-12 13:37:50 +00001127llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1128 SourceLocation Loc, unsigned IVSize,
1129 bool IVSigned, llvm::Value *IL,
1130 llvm::Value *LB, llvm::Value *UB,
1131 llvm::Value *ST) {
1132 // Call __kmpc_dispatch_next(
1133 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1134 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1135 // kmp_int[32|64] *p_stride);
1136 llvm::Value *Args[] = {
1137 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1138 IL, // &isLastIter
1139 LB, // &Lower
1140 UB, // &Upper
1141 ST // &Stride
1142 };
1143 llvm::Value *Call =
1144 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1145 return CGF.EmitScalarConversion(
1146 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1147 CGF.getContext().BoolTy);
1148}
1149
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001150void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1151 llvm::Value *NumThreads,
1152 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001153 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1154 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001155 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001156 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001157 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1158 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001159}
1160
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001161void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1162 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001163 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001164 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1165 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001166}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001167
Alexey Bataev62b63b12015-03-10 07:28:44 +00001168namespace {
1169/// \brief Indexes of fields for type kmp_task_t.
1170enum KmpTaskTFields {
1171 /// \brief List of shared variables.
1172 KmpTaskTShareds,
1173 /// \brief Task routine.
1174 KmpTaskTRoutine,
1175 /// \brief Partition id for the untied tasks.
1176 KmpTaskTPartId,
1177 /// \brief Function with call of destructors for private variables.
1178 KmpTaskTDestructors,
1179};
1180} // namespace
1181
1182void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1183 if (!KmpRoutineEntryPtrTy) {
1184 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1185 auto &C = CGM.getContext();
1186 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1187 FunctionProtoType::ExtProtoInfo EPI;
1188 KmpRoutineEntryPtrQTy = C.getPointerType(
1189 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1190 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1191 }
1192}
1193
1194static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1195 QualType FieldTy) {
1196 auto *Field = FieldDecl::Create(
1197 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1198 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1199 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1200 Field->setAccess(AS_public);
1201 DC->addDecl(Field);
1202}
1203
1204static QualType createKmpTaskTRecordDecl(CodeGenModule &CGM,
1205 QualType KmpInt32Ty,
1206 QualType KmpRoutineEntryPointerQTy) {
1207 auto &C = CGM.getContext();
1208 // Build struct kmp_task_t {
1209 // void * shareds;
1210 // kmp_routine_entry_t routine;
1211 // kmp_int32 part_id;
1212 // kmp_routine_entry_t destructors;
1213 // /* private vars */
1214 // };
1215 auto *RD = C.buildImplicitRecord("kmp_task_t");
1216 RD->startDefinition();
1217 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1218 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1219 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1220 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1221 // TODO: add private fields.
1222 RD->completeDefinition();
1223 return C.getRecordType(RD);
1224}
1225
1226/// \brief Emit a proxy function which accepts kmp_task_t as the second
1227/// argument.
1228/// \code
1229/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1230/// TaskFunction(gtid, tt->part_id, tt->shareds);
1231/// return 0;
1232/// }
1233/// \endcode
1234static llvm::Value *
1235emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
1236 QualType KmpInt32Ty, QualType KmpTaskTPtrQTy,
1237 QualType SharedsPtrTy, llvm::Value *TaskFunction) {
1238 auto &C = CGM.getContext();
1239 FunctionArgList Args;
1240 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1241 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
1242 /*Id=*/nullptr, KmpTaskTPtrQTy);
1243 Args.push_back(&GtidArg);
1244 Args.push_back(&TaskTypeArg);
1245 FunctionType::ExtInfo Info;
1246 auto &TaskEntryFnInfo =
1247 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1248 /*isVariadic=*/false);
1249 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1250 auto *TaskEntry =
1251 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1252 ".omp_task_entry.", &CGM.getModule());
1253 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1254 CodeGenFunction CGF(CGM);
1255 CGF.disableDebugInfo();
1256 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1257
1258 // TaskFunction(gtid, tt->part_id, tt->shareds);
1259 auto *GtidParam = CGF.EmitLoadOfScalar(
1260 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1261 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1262 auto TaskTypeArgAddr = CGF.EmitLoadOfScalar(
1263 CGF.GetAddrOfLocalVar(&TaskTypeArg), /*Volatile=*/false,
1264 CGM.PointerAlignInBytes, KmpTaskTPtrQTy, Loc);
1265 auto *PartidPtr = CGF.Builder.CreateStructGEP(TaskTypeArgAddr,
1266 /*Idx=*/KmpTaskTPartId);
1267 auto *PartidParam = CGF.EmitLoadOfScalar(
1268 PartidPtr, /*Volatile=*/false,
1269 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1270 auto *SharedsPtr = CGF.Builder.CreateStructGEP(TaskTypeArgAddr,
1271 /*Idx=*/KmpTaskTShareds);
1272 auto *SharedsParam =
1273 CGF.EmitLoadOfScalar(SharedsPtr, /*Volatile=*/false,
1274 CGM.PointerAlignInBytes, C.VoidPtrTy, Loc);
1275 llvm::Value *CallArgs[] = {
1276 GtidParam, PartidParam,
1277 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1278 SharedsParam, CGF.ConvertTypeForMem(SharedsPtrTy))};
1279 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1280 CGF.EmitStoreThroughLValue(
1281 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1282 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1283 CGF.FinishFunction();
1284 return TaskEntry;
1285}
1286
1287void CGOpenMPRuntime::emitTaskCall(
1288 CodeGenFunction &CGF, SourceLocation Loc, bool Tied,
1289 llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
1290 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds) {
1291 auto &C = CGM.getContext();
1292 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1293 // Build type kmp_routine_entry_t (if not built yet).
1294 emitKmpRoutineEntryT(KmpInt32Ty);
1295 // Build particular struct kmp_task_t for the given task.
1296 auto KmpTaskQTy =
1297 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy);
1298 QualType KmpTaskTPtrQTy = C.getPointerType(KmpTaskQTy);
1299 auto KmpTaskTPtrTy = CGF.ConvertType(KmpTaskQTy)->getPointerTo();
1300 auto KmpTaskTySize = CGM.getSize(C.getTypeSizeInChars(KmpTaskQTy));
1301 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
1302
1303 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
1304 // kmp_task_t *tt);
1305 auto *TaskEntry = emitProxyTaskFunction(CGM, Loc, KmpInt32Ty, KmpTaskTPtrQTy,
1306 SharedsPtrTy, TaskFunction);
1307
1308 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1309 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1310 // kmp_routine_entry_t *task_entry);
1311 // Task flags. Format is taken from
1312 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
1313 // description of kmp_tasking_flags struct.
1314 const unsigned TiedFlag = 0x1;
1315 const unsigned FinalFlag = 0x2;
1316 unsigned Flags = Tied ? TiedFlag : 0;
1317 auto *TaskFlags =
1318 Final.getPointer()
1319 ? CGF.Builder.CreateSelect(Final.getPointer(),
1320 CGF.Builder.getInt32(FinalFlag),
1321 CGF.Builder.getInt32(/*C=*/0))
1322 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
1323 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
1324 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
1325 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
1326 getThreadID(CGF, Loc), TaskFlags, KmpTaskTySize,
1327 CGM.getSize(SharedsSize),
1328 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1329 TaskEntry, KmpRoutineEntryPtrTy)};
1330 auto *NewTask = CGF.EmitRuntimeCall(
1331 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
1332 auto *NewTaskNewTaskTTy =
1333 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NewTask, KmpTaskTPtrTy);
1334 // Fill the data in the resulting kmp_task_t record.
1335 // Copy shareds if there are any.
1336 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty())
1337 CGF.EmitAggregateCopy(
1338 CGF.EmitLoadOfScalar(
1339 CGF.Builder.CreateStructGEP(NewTaskNewTaskTTy,
1340 /*Idx=*/KmpTaskTShareds),
1341 /*Volatile=*/false, CGM.PointerAlignInBytes, SharedsPtrTy, Loc),
1342 Shareds, SharedsTy);
1343 // TODO: generate function with destructors for privates.
1344 // Provide pointer to function with destructors for privates.
1345 CGF.Builder.CreateAlignedStore(
1346 llvm::ConstantPointerNull::get(
1347 cast<llvm::PointerType>(KmpRoutineEntryPtrTy)),
1348 CGF.Builder.CreateStructGEP(NewTaskNewTaskTTy,
1349 /*Idx=*/KmpTaskTDestructors),
1350 CGM.PointerAlignInBytes);
1351
1352 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
1353 // libcall.
1354 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1355 // *new_task);
1356 llvm::Value *TaskArgs[] = {emitUpdateLocation(CGF, Loc),
1357 getThreadID(CGF, Loc), NewTask};
1358 // TODO: add check for untied tasks.
1359 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1360}
1361
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001362InlinedOpenMPRegionRAII::InlinedOpenMPRegionRAII(
1363 CodeGenFunction &CGF, const OMPExecutableDirective &D)
1364 : CGF(CGF) {
1365 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(D, CGF.CapturedStmtInfo);
Alexey Bataev36bf0112015-03-10 05:15:26 +00001366 // 1.2.2 OpenMP Language Terminology
1367 // Structured block - An executable statement with a single entry at the
1368 // top and a single exit at the bottom.
1369 // The point of exit cannot be a branch out of the structured block.
1370 // longjmp() and throw() must not violate the entry/exit criteria.
1371 CGF.EHStack.pushTerminate();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001372}
1373
1374InlinedOpenMPRegionRAII::~InlinedOpenMPRegionRAII() {
Alexey Bataev36bf0112015-03-10 05:15:26 +00001375 CGF.EHStack.popTerminate();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001376 auto *OldCSI =
1377 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
1378 delete CGF.CapturedStmtInfo;
1379 CGF.CapturedStmtInfo = OldCSI;
1380}
1381