blob: f3a575f117d63b894230d242cadee8d4551f63b7 [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 Bataev6f1ffc02015-04-10 04:50:10 +000034 /// \brief Kinds of OpenMP regions used in codegen.
35 enum CGOpenMPRegionKind {
36 /// \brief Region with outlined function for standalone 'parallel'
37 /// directive.
38 ParallelOutlinedRegion,
39 /// \brief Region with outlined function for standalone 'task' directive.
40 TaskOutlinedRegion,
41 /// \brief Region for constructs that do not require function outlining,
42 /// like 'for', 'sections', 'atomic' etc. directives.
43 InlinedRegion,
44 };
Alexey Bataev18095712014-10-10 12:19:54 +000045
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 CGOpenMPRegionInfo(const CapturedStmt &CS,
47 const CGOpenMPRegionKind RegionKind,
48 const RegionCodeGenTy &CodeGen)
49 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
50 CodeGen(CodeGen) {}
51
52 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
53 const RegionCodeGenTy &CodeGen)
54 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind),
55 CodeGen(CodeGen) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000056
57 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000058 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000059 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000060
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000061 /// \brief Emit the captured statement body.
62 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
63
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000065 /// \return LValue for thread id variable. This LValue always has type int32*.
66 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000069
Alexey Bataev18095712014-10-10 12:19:54 +000070 static bool classof(const CGCapturedStmtInfo *Info) {
71 return Info->getKind() == CR_OpenMP;
72 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000073
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000074protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000075 CGOpenMPRegionKind RegionKind;
76 const RegionCodeGenTy &CodeGen;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000077};
Alexey Bataev18095712014-10-10 12:19:54 +000078
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079/// \brief API for captured statement code generation in OpenMP constructs.
80class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
81public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000082 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
83 const RegionCodeGenTy &CodeGen)
84 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen),
85 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000086 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
87 }
88 /// \brief Get a variable or parameter for storing global thread id
89 /// inside OpenMP construct.
90 virtual const VarDecl *getThreadIDVariable() const override {
91 return ThreadIDVar;
92 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000093
Alexey Bataev18095712014-10-10 12:19:54 +000094 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +000095 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +000096
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000097 static bool classof(const CGCapturedStmtInfo *Info) {
98 return CGOpenMPRegionInfo::classof(Info) &&
99 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
100 ParallelOutlinedRegion;
101 }
102
Alexey Bataev18095712014-10-10 12:19:54 +0000103private:
104 /// \brief A variable or parameter storing global thread id for OpenMP
105 /// constructs.
106 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000107};
108
Alexey Bataev62b63b12015-03-10 07:28:44 +0000109/// \brief API for captured statement code generation in OpenMP constructs.
110class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
111public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000112 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000113 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114 const RegionCodeGenTy &CodeGen)
115 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen),
116 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000117 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
118 }
119 /// \brief Get a variable or parameter for storing global thread id
120 /// inside OpenMP construct.
121 virtual const VarDecl *getThreadIDVariable() const override {
122 return ThreadIDVar;
123 }
124
125 /// \brief Get an LValue for the current ThreadID variable.
126 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
127
Alexey Bataev62b63b12015-03-10 07:28:44 +0000128 /// \brief Get the name of the capture helper.
129 StringRef getHelperName() const override { return ".omp_outlined."; }
130
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000131 static bool classof(const CGCapturedStmtInfo *Info) {
132 return CGOpenMPRegionInfo::classof(Info) &&
133 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
134 TaskOutlinedRegion;
135 }
136
Alexey Bataev62b63b12015-03-10 07:28:44 +0000137private:
138 /// \brief A variable or parameter storing global thread id for OpenMP
139 /// constructs.
140 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000141};
142
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000143/// \brief API for inlined captured statement code generation in OpenMP
144/// constructs.
145class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
146public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000147 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
148 const RegionCodeGenTy &CodeGen)
149 : CGOpenMPRegionInfo(InlinedRegion, CodeGen), OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000150 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
151 // \brief Retrieve the value of the context parameter.
152 virtual llvm::Value *getContextValue() const override {
153 if (OuterRegionInfo)
154 return OuterRegionInfo->getContextValue();
155 llvm_unreachable("No context value for inlined OpenMP region");
156 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000157 virtual void setContextValue(llvm::Value *V) override {
158 if (OuterRegionInfo) {
159 OuterRegionInfo->setContextValue(V);
160 return;
161 }
162 llvm_unreachable("No context value for inlined OpenMP region");
163 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000164 /// \brief Lookup the captured field decl for a variable.
165 virtual const FieldDecl *lookup(const VarDecl *VD) const override {
166 if (OuterRegionInfo)
167 return OuterRegionInfo->lookup(VD);
168 llvm_unreachable("Trying to reference VarDecl that is neither local nor "
169 "captured in outer OpenMP region");
170 }
171 virtual FieldDecl *getThisFieldDecl() const override {
172 if (OuterRegionInfo)
173 return OuterRegionInfo->getThisFieldDecl();
174 return nullptr;
175 }
176 /// \brief Get a variable or parameter for storing global thread id
177 /// inside OpenMP construct.
178 virtual const VarDecl *getThreadIDVariable() const override {
179 if (OuterRegionInfo)
180 return OuterRegionInfo->getThreadIDVariable();
181 return nullptr;
182 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000183
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000184 /// \brief Get the name of the capture helper.
185 virtual StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000186 if (auto *OuterRegionInfo = getOldCSI())
187 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000188 llvm_unreachable("No helper name for inlined OpenMP construct");
189 }
190
191 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
192
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000193 static bool classof(const CGCapturedStmtInfo *Info) {
194 return CGOpenMPRegionInfo::classof(Info) &&
195 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
196 }
197
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000198private:
199 /// \brief CodeGen info about outer OpenMP region.
200 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
201 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000202};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000203
204/// \brief RAII for emitting code of OpenMP constructs.
205class InlinedOpenMPRegionRAII {
206 CodeGenFunction &CGF;
207
208public:
209 /// \brief Constructs region for combined constructs.
210 /// \param CodeGen Code generation sequence for combined directives. Includes
211 /// a list of functions used for code generation of implicitly inlined
212 /// regions.
213 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen)
214 : CGF(CGF) {
215 // Start emission for the construct.
216 CGF.CapturedStmtInfo =
217 new CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, CodeGen);
218 }
219 ~InlinedOpenMPRegionRAII() {
220 // Restore original CapturedStmtInfo only if we're done with code emission.
221 auto *OldCSI =
222 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
223 delete CGF.CapturedStmtInfo;
224 CGF.CapturedStmtInfo = OldCSI;
225 }
226};
227
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000228} // namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000229
230LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
231 return CGF.MakeNaturalAlignAddrLValue(
Alexey Bataev62b63b12015-03-10 07:28:44 +0000232 CGF.Builder.CreateAlignedLoad(
233 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
234 CGF.PointerAlignInBytes),
235 getThreadIDVariable()
236 ->getType()
237 ->castAs<PointerType>()
238 ->getPointeeType());
Alexey Bataev18095712014-10-10 12:19:54 +0000239}
240
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000241void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
242 // 1.2.2 OpenMP Language Terminology
243 // Structured block - An executable statement with a single entry at the
244 // top and a single exit at the bottom.
245 // The point of exit cannot be a branch out of the structured block.
246 // longjmp() and throw() must not violate the entry/exit criteria.
247 CGF.EHStack.pushTerminate();
248 {
249 CodeGenFunction::RunCleanupsScope Scope(CGF);
250 CodeGen(CGF);
251 }
252 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000253}
254
Alexey Bataev62b63b12015-03-10 07:28:44 +0000255LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
256 CodeGenFunction &CGF) {
257 return CGF.MakeNaturalAlignAddrLValue(
258 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
259 getThreadIDVariable()->getType());
260}
261
Alexey Bataev9959db52014-05-06 10:08:46 +0000262CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataev62b63b12015-03-10 07:28:44 +0000263 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000264 IdentTy = llvm::StructType::create(
265 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
266 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000267 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000268 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000269 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
270 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000271 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000272 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Alexey Bataev9959db52014-05-06 10:08:46 +0000273}
274
Alexey Bataev91797552015-03-18 04:13:55 +0000275void CGOpenMPRuntime::clear() {
276 InternalVars.clear();
277}
278
Alexey Bataev9959db52014-05-06 10:08:46 +0000279llvm::Value *
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000280CGOpenMPRuntime::emitParallelOutlinedFunction(const OMPExecutableDirective &D,
281 const VarDecl *ThreadIDVar,
282 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000283 assert(ThreadIDVar->getType()->isPointerType() &&
284 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000285 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
286 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000287 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataev18095712014-10-10 12:19:54 +0000288 CGF.CapturedStmtInfo = &CGInfo;
289 return CGF.GenerateCapturedStmtFunction(*CS);
290}
291
292llvm::Value *
Alexey Bataev62b63b12015-03-10 07:28:44 +0000293CGOpenMPRuntime::emitTaskOutlinedFunction(const OMPExecutableDirective &D,
294 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000295 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000296 assert(!ThreadIDVar->getType()->isPointerType() &&
297 "thread id variable must be of type kmp_int32 for tasks");
298 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
299 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000300 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000301 CGF.CapturedStmtInfo = &CGInfo;
302 return CGF.GenerateCapturedStmtFunction(*CS);
303}
304
305llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000306CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000307 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000308 if (!Entry) {
309 if (!DefaultOpenMPPSource) {
310 // Initialize default location for psource field of ident_t structure of
311 // all ident_t objects. Format is ";file;function;line;column;;".
312 // Taken from
313 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
314 DefaultOpenMPPSource =
315 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
316 DefaultOpenMPPSource =
317 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
318 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000319 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
320 CGM.getModule(), IdentTy, /*isConstant*/ true,
321 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000322 DefaultOpenMPLocation->setUnnamedAddr(true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000323
324 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000325 llvm::Constant *Values[] = {Zero,
326 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
327 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000328 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
329 DefaultOpenMPLocation->setInitializer(Init);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000330 OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000331 return DefaultOpenMPLocation;
332 }
333 return Entry;
334}
335
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000336llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
337 SourceLocation Loc,
338 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000339 // If no debug info is generated - return global default location.
340 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
341 Loc.isInvalid())
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000342 return getOrCreateDefaultLocation(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000343
344 assert(CGF.CurFn && "No function in current CodeGenFunction.");
345
Alexey Bataev9959db52014-05-06 10:08:46 +0000346 llvm::Value *LocValue = nullptr;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000347 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
348 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataev18095712014-10-10 12:19:54 +0000349 LocValue = I->second.DebugLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +0000350 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
351 // GetOpenMPThreadID was called before this routine.
352 if (LocValue == nullptr) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000353 // Generate "ident_t .kmpc_loc.addr;"
354 llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
Alexey Bataev9959db52014-05-06 10:08:46 +0000355 AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
Alexey Bataev18095712014-10-10 12:19:54 +0000356 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
357 Elem.second.DebugLoc = AI;
Alexey Bataev9959db52014-05-06 10:08:46 +0000358 LocValue = AI;
359
360 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
361 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000362 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataev9959db52014-05-06 10:08:46 +0000363 llvm::ConstantExpr::getSizeOf(IdentTy),
364 CGM.PointerAlignInBytes);
365 }
366
367 // char **psource = &.kmpc_loc_<flags>.addr.psource;
David Blaikie1ed728c2015-04-05 22:45:47 +0000368 auto *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(IdentTy, LocValue, 0,
369 IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000370
Alexey Bataevf002aca2014-05-30 05:48:40 +0000371 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
372 if (OMPDebugLoc == nullptr) {
373 SmallString<128> Buffer2;
374 llvm::raw_svector_ostream OS2(Buffer2);
375 // Build debug location
376 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
377 OS2 << ";" << PLoc.getFilename() << ";";
378 if (const FunctionDecl *FD =
379 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
380 OS2 << FD->getQualifiedNameAsString();
381 }
382 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
383 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
384 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000385 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000386 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000387 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
388
Alexey Bataev9959db52014-05-06 10:08:46 +0000389 return LocValue;
390}
391
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000392llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
393 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000394 assert(CGF.CurFn && "No function in current CodeGenFunction.");
395
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000396 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000397 // Check whether we've already cached a load of the thread id in this
398 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000399 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000400 if (I != OpenMPLocThreadIDMap.end()) {
401 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000402 if (ThreadID != nullptr)
403 return ThreadID;
404 }
405 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000406 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000407 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000408 // Check if this an outlined function with thread id passed as argument.
409 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000410 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
411 // If value loaded in entry block, cache it and use it everywhere in
412 // function.
413 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
414 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
415 Elem.second.ThreadID = ThreadID;
416 }
417 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000418 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000419 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000420
421 // This is not an outlined function region - need to call __kmpc_int32
422 // kmpc_global_thread_num(ident_t *loc).
423 // Generate thread id value and cache this value for use across the
424 // function.
425 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
426 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
427 ThreadID =
428 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
429 emitUpdateLocation(CGF, Loc));
430 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
431 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000432 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000433}
434
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000435void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000436 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000437 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
438 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000439}
440
441llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
442 return llvm::PointerType::getUnqual(IdentTy);
443}
444
445llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
446 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
447}
448
449llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000450CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000451 llvm::Constant *RTLFn = nullptr;
452 switch (Function) {
453 case OMPRTL__kmpc_fork_call: {
454 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
455 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000456 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
457 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000458 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000459 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000460 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
461 break;
462 }
463 case OMPRTL__kmpc_global_thread_num: {
464 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000465 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000466 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000467 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000468 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
469 break;
470 }
Alexey Bataev97720002014-11-11 04:05:39 +0000471 case OMPRTL__kmpc_threadprivate_cached: {
472 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
473 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
474 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
475 CGM.VoidPtrTy, CGM.SizeTy,
476 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
477 llvm::FunctionType *FnTy =
478 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
479 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
480 break;
481 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000482 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000483 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
484 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000485 llvm::Type *TypeParams[] = {
486 getIdentTyPointerTy(), CGM.Int32Ty,
487 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
488 llvm::FunctionType *FnTy =
489 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
490 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
491 break;
492 }
Alexey Bataev97720002014-11-11 04:05:39 +0000493 case OMPRTL__kmpc_threadprivate_register: {
494 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
495 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
496 // typedef void *(*kmpc_ctor)(void *);
497 auto KmpcCtorTy =
498 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
499 /*isVarArg*/ false)->getPointerTo();
500 // typedef void *(*kmpc_cctor)(void *, void *);
501 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
502 auto KmpcCopyCtorTy =
503 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
504 /*isVarArg*/ false)->getPointerTo();
505 // typedef void (*kmpc_dtor)(void *);
506 auto KmpcDtorTy =
507 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
508 ->getPointerTo();
509 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
510 KmpcCopyCtorTy, KmpcDtorTy};
511 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
512 /*isVarArg*/ false);
513 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
514 break;
515 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000516 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000517 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
518 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000519 llvm::Type *TypeParams[] = {
520 getIdentTyPointerTy(), CGM.Int32Ty,
521 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
522 llvm::FunctionType *FnTy =
523 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
524 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
525 break;
526 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000527 case OMPRTL__kmpc_cancel_barrier: {
528 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
529 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000530 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
531 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000532 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
533 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000534 break;
535 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000536 case OMPRTL__kmpc_for_static_fini: {
537 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
538 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
539 llvm::FunctionType *FnTy =
540 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
541 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
542 break;
543 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000544 case OMPRTL__kmpc_push_num_threads: {
545 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
546 // kmp_int32 num_threads)
547 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
548 CGM.Int32Ty};
549 llvm::FunctionType *FnTy =
550 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
551 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
552 break;
553 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000554 case OMPRTL__kmpc_serialized_parallel: {
555 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
556 // global_tid);
557 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
558 llvm::FunctionType *FnTy =
559 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
560 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
561 break;
562 }
563 case OMPRTL__kmpc_end_serialized_parallel: {
564 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
565 // global_tid);
566 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
567 llvm::FunctionType *FnTy =
568 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
569 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
570 break;
571 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000572 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000573 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000574 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
575 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000576 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000577 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
578 break;
579 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000580 case OMPRTL__kmpc_master: {
581 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
582 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
583 llvm::FunctionType *FnTy =
584 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
585 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
586 break;
587 }
588 case OMPRTL__kmpc_end_master: {
589 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
590 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
591 llvm::FunctionType *FnTy =
592 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
593 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
594 break;
595 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000596 case OMPRTL__kmpc_omp_taskyield: {
597 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
598 // int end_part);
599 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
600 llvm::FunctionType *FnTy =
601 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
602 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
603 break;
604 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000605 case OMPRTL__kmpc_single: {
606 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
607 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
608 llvm::FunctionType *FnTy =
609 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
610 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
611 break;
612 }
613 case OMPRTL__kmpc_end_single: {
614 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
615 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
616 llvm::FunctionType *FnTy =
617 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
618 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
619 break;
620 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000621 case OMPRTL__kmpc_omp_task_alloc: {
622 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
623 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
624 // kmp_routine_entry_t *task_entry);
625 assert(KmpRoutineEntryPtrTy != nullptr &&
626 "Type kmp_routine_entry_t must be created.");
627 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
628 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
629 // Return void * and then cast to particular kmp_task_t type.
630 llvm::FunctionType *FnTy =
631 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
632 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
633 break;
634 }
635 case OMPRTL__kmpc_omp_task: {
636 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
637 // *new_task);
638 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
639 CGM.VoidPtrTy};
640 llvm::FunctionType *FnTy =
641 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
642 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
643 break;
644 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000645 case OMPRTL__kmpc_copyprivate: {
646 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
647 // kmp_int32 cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
648 // kmp_int32 didit);
649 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
650 auto *CpyFnTy =
651 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
652 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
653 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
654 CGM.Int32Ty};
655 llvm::FunctionType *FnTy =
656 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
657 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
658 break;
659 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000660 }
661 return RTLFn;
662}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000663
Alexander Musman21212e42015-03-13 10:38:23 +0000664llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
665 bool IVSigned) {
666 assert((IVSize == 32 || IVSize == 64) &&
667 "IV size is not compatible with the omp runtime");
668 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
669 : "__kmpc_for_static_init_4u")
670 : (IVSigned ? "__kmpc_for_static_init_8"
671 : "__kmpc_for_static_init_8u");
672 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
673 auto PtrTy = llvm::PointerType::getUnqual(ITy);
674 llvm::Type *TypeParams[] = {
675 getIdentTyPointerTy(), // loc
676 CGM.Int32Ty, // tid
677 CGM.Int32Ty, // schedtype
678 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
679 PtrTy, // p_lower
680 PtrTy, // p_upper
681 PtrTy, // p_stride
682 ITy, // incr
683 ITy // chunk
684 };
685 llvm::FunctionType *FnTy =
686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
687 return CGM.CreateRuntimeFunction(FnTy, Name);
688}
689
Alexander Musman92bdaab2015-03-12 13:37:50 +0000690llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
691 bool IVSigned) {
692 assert((IVSize == 32 || IVSize == 64) &&
693 "IV size is not compatible with the omp runtime");
694 auto Name =
695 IVSize == 32
696 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
697 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
698 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
699 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
700 CGM.Int32Ty, // tid
701 CGM.Int32Ty, // schedtype
702 ITy, // lower
703 ITy, // upper
704 ITy, // stride
705 ITy // chunk
706 };
707 llvm::FunctionType *FnTy =
708 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
709 return CGM.CreateRuntimeFunction(FnTy, Name);
710}
711
712llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
713 bool IVSigned) {
714 assert((IVSize == 32 || IVSize == 64) &&
715 "IV size is not compatible with the omp runtime");
716 auto Name =
717 IVSize == 32
718 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
719 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
720 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
721 auto PtrTy = llvm::PointerType::getUnqual(ITy);
722 llvm::Type *TypeParams[] = {
723 getIdentTyPointerTy(), // loc
724 CGM.Int32Ty, // tid
725 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
726 PtrTy, // p_lower
727 PtrTy, // p_upper
728 PtrTy // p_stride
729 };
730 llvm::FunctionType *FnTy =
731 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
732 return CGM.CreateRuntimeFunction(FnTy, Name);
733}
734
Alexey Bataev97720002014-11-11 04:05:39 +0000735llvm::Constant *
736CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
737 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000738 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000739 Twine(CGM.getMangledName(VD)) + ".cache.");
740}
741
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000742llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
743 const VarDecl *VD,
744 llvm::Value *VDAddr,
745 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000746 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000747 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000748 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
749 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
750 getOrCreateThreadPrivateCache(VD)};
751 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000752 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000753}
754
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000755void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000756 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
757 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
758 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
759 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000760 auto OMPLoc = emitUpdateLocation(CGF, Loc);
761 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000762 OMPLoc);
763 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
764 // to register constructor/destructor for variable.
765 llvm::Value *Args[] = {OMPLoc,
766 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
767 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000768 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000769 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000770}
771
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000772llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000773 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
774 bool PerformInit, CodeGenFunction *CGF) {
775 VD = VD->getDefinition(CGM.getContext());
776 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
777 ThreadPrivateWithDefinition.insert(VD);
778 QualType ASTTy = VD->getType();
779
780 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
781 auto Init = VD->getAnyInitializer();
782 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
783 // Generate function that re-emits the declaration's initializer into the
784 // threadprivate copy of the variable VD
785 CodeGenFunction CtorCGF(CGM);
786 FunctionArgList Args;
787 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
788 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
789 Args.push_back(&Dst);
790
791 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
792 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
793 /*isVariadic=*/false);
794 auto FTy = CGM.getTypes().GetFunctionType(FI);
795 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
796 FTy, ".__kmpc_global_ctor_.", Loc);
797 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
798 Args, SourceLocation());
799 auto ArgVal = CtorCGF.EmitLoadOfScalar(
800 CtorCGF.GetAddrOfLocalVar(&Dst),
801 /*Volatile=*/false, CGM.PointerAlignInBytes,
802 CGM.getContext().VoidPtrTy, Dst.getLocation());
803 auto Arg = CtorCGF.Builder.CreatePointerCast(
804 ArgVal,
805 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
806 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
807 /*IsInitializer=*/true);
808 ArgVal = CtorCGF.EmitLoadOfScalar(
809 CtorCGF.GetAddrOfLocalVar(&Dst),
810 /*Volatile=*/false, CGM.PointerAlignInBytes,
811 CGM.getContext().VoidPtrTy, Dst.getLocation());
812 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
813 CtorCGF.FinishFunction();
814 Ctor = Fn;
815 }
816 if (VD->getType().isDestructedType() != QualType::DK_none) {
817 // Generate function that emits destructor call for the threadprivate copy
818 // of the variable VD
819 CodeGenFunction DtorCGF(CGM);
820 FunctionArgList Args;
821 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
822 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
823 Args.push_back(&Dst);
824
825 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
826 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
827 /*isVariadic=*/false);
828 auto FTy = CGM.getTypes().GetFunctionType(FI);
829 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
830 FTy, ".__kmpc_global_dtor_.", Loc);
831 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
832 SourceLocation());
833 auto ArgVal = DtorCGF.EmitLoadOfScalar(
834 DtorCGF.GetAddrOfLocalVar(&Dst),
835 /*Volatile=*/false, CGM.PointerAlignInBytes,
836 CGM.getContext().VoidPtrTy, Dst.getLocation());
837 DtorCGF.emitDestroy(ArgVal, ASTTy,
838 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
839 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
840 DtorCGF.FinishFunction();
841 Dtor = Fn;
842 }
843 // Do not emit init function if it is not required.
844 if (!Ctor && !Dtor)
845 return nullptr;
846
847 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
848 auto CopyCtorTy =
849 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
850 /*isVarArg=*/false)->getPointerTo();
851 // Copying constructor for the threadprivate variable.
852 // Must be NULL - reserved by runtime, but currently it requires that this
853 // parameter is always NULL. Otherwise it fires assertion.
854 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
855 if (Ctor == nullptr) {
856 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
857 /*isVarArg=*/false)->getPointerTo();
858 Ctor = llvm::Constant::getNullValue(CtorTy);
859 }
860 if (Dtor == nullptr) {
861 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
862 /*isVarArg=*/false)->getPointerTo();
863 Dtor = llvm::Constant::getNullValue(DtorTy);
864 }
865 if (!CGF) {
866 auto InitFunctionTy =
867 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
868 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
869 InitFunctionTy, ".__omp_threadprivate_init_.");
870 CodeGenFunction InitCGF(CGM);
871 FunctionArgList ArgList;
872 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
873 CGM.getTypes().arrangeNullaryFunction(), ArgList,
874 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000875 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000876 InitCGF.FinishFunction();
877 return InitFunction;
878 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000879 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +0000880 }
881 return nullptr;
882}
883
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000884void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
885 llvm::Value *OutlinedFn,
886 llvm::Value *CapturedStruct) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000887 // Build call __kmpc_fork_call(loc, 1, microtask, captured_struct/*context*/)
888 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000889 emitUpdateLocation(CGF, Loc),
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000890 CGF.Builder.getInt32(1), // Number of arguments after 'microtask' argument
891 // (there is only one additional argument - 'context')
892 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
893 CGF.EmitCastToVoidPtr(CapturedStruct)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000894 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000895 CGF.EmitRuntimeCall(RTLFn, Args);
896}
897
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000898void CGOpenMPRuntime::emitSerialCall(CodeGenFunction &CGF, SourceLocation Loc,
899 llvm::Value *OutlinedFn,
900 llvm::Value *CapturedStruct) {
901 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000902 // Build calls:
903 // __kmpc_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000904 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), ThreadID};
905 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
906 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000907
908 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000909 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000910 auto Int32Ty =
911 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
912 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
913 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
914 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
915 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
916
917 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000918 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
919 CGF.EmitRuntimeCall(
920 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000921}
922
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +0000923// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +0000924// thread-ID variable (it is passed in a first argument of the outlined function
925// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
926// regular serial code region, get thread ID by calling kmp_int32
927// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
928// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000929llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +0000930 SourceLocation Loc) {
931 if (auto OMPRegionInfo =
932 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000933 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +0000934 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000935
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000936 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +0000937 auto Int32Ty =
938 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
939 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
940 CGF.EmitStoreOfScalar(ThreadID,
941 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
942
943 return ThreadIDTemp;
944}
945
Alexey Bataev97720002014-11-11 04:05:39 +0000946llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000947CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +0000948 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000949 SmallString<256> Buffer;
950 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +0000951 Out << Name;
952 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +0000953 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
954 if (Elem.second) {
955 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +0000956 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +0000957 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +0000958 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000959
David Blaikie13156b62014-11-19 03:06:06 +0000960 return Elem.second = new llvm::GlobalVariable(
961 CGM.getModule(), Ty, /*IsConstant*/ false,
962 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
963 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +0000964}
965
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000966llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +0000967 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000968 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000969}
970
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000971namespace {
972class CallEndCleanup : public EHScopeStack::Cleanup {
973private:
974 const RegionCodeGenTy CodeGen;
975
976public:
977 CallEndCleanup(const RegionCodeGenTy &CodeGen) : CodeGen(CodeGen) {}
978 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override { CodeGen(CGF); }
979};
980} // namespace
981
982void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
983 StringRef CriticalName,
984 const RegionCodeGenTy &CriticalOpGen,
985 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +0000986 // __kmpc_critical(ident_t *, gtid, Lock);
987 // CriticalOpGen();
988 // __kmpc_end_critical(ident_t *, gtid, Lock);
989 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000990 {
991 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +0000992 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
993 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000994 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
995 emitInlinedDirective(CGF, CriticalOpGen);
996 // Build a call to __kmpc_end_critical
997 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataevd7614fb2015-04-10 06:33:45 +0000998 NormalAndEHCleanup, [Loc, CriticalName](CodeGenFunction &CGF) {
999 llvm::Value *Args[] = {
1000 CGF.CGM.getOpenMPRuntime().emitUpdateLocation(CGF, Loc),
1001 CGF.CGM.getOpenMPRuntime().getThreadID(CGF, Loc),
1002 CGF.CGM.getOpenMPRuntime().getCriticalRegionLock(CriticalName)};
1003 CGF.EmitRuntimeCall(CGF.CGM.getOpenMPRuntime().createRuntimeFunction(
1004 OMPRTL__kmpc_end_critical),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001005 Args);
1006 });
1007 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001008}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001009
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001010static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001011 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001012 llvm::Value *CallBool = CGF.EmitScalarConversion(
1013 IfCond,
1014 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
1015 CGF.getContext().BoolTy);
1016
1017 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1018 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1019 // Generate the branch (If-stmt)
1020 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1021 CGF.EmitBlock(ThenBlock);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001022 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001023 // Emit the rest of bblocks/branches
1024 CGF.EmitBranch(ContBlock);
1025 CGF.EmitBlock(ContBlock, true);
1026}
1027
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001028void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001029 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001030 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001031 // if(__kmpc_master(ident_t *, gtid)) {
1032 // MasterOpGen();
1033 // __kmpc_end_master(ident_t *, gtid);
1034 // }
1035 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001036 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001037 auto *IsMaster =
1038 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001039 emitIfStmt(CGF, IsMaster, [&](CodeGenFunction &CGF) -> void {
1040 CodeGenFunction::RunCleanupsScope Scope(CGF);
1041 MasterOpGen(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00001042 // Build a call to __kmpc_end_master.
1043 // OpenMP [1.2.2 OpenMP Language Terminology]
1044 // For C/C++, an executable statement, possibly compound, with a single
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001045 // entry at the top and a single exit at the bottom, or an OpenMP
1046 // construct.
Alexey Bataev8d690652014-12-04 07:23:53 +00001047 // * Access to the structured block must not be the result of a branch.
1048 // * The point of exit cannot be a branch out of the structured block.
1049 // * The point of entry must not be a call to setjmp().
1050 // * longjmp() and throw() must not violate the entry/exit criteria.
1051 // * An expression statement, iteration statement, selection statement, or
1052 // try block is considered to be a structured block if the corresponding
1053 // compound statement obtained by enclosing it in { and } would be a
1054 // structured block.
1055 // It is analyzed in Sema, so we can just call __kmpc_end_master() on
1056 // fallthrough rather than pushing a normal cleanup for it.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001057 // Build a call to __kmpc_end_critical
1058 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001059 NormalAndEHCleanup, [Loc](CodeGenFunction &CGF) {
1060 llvm::Value *Args[] = {
1061 CGF.CGM.getOpenMPRuntime().emitUpdateLocation(CGF, Loc),
1062 CGF.CGM.getOpenMPRuntime().getThreadID(CGF, Loc)};
1063 CGF.EmitRuntimeCall(CGF.CGM.getOpenMPRuntime().createRuntimeFunction(
1064 OMPRTL__kmpc_end_master),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001065 Args);
1066 });
Alexey Bataev8d690652014-12-04 07:23:53 +00001067 });
1068}
1069
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001070void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1071 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001072 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1073 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001074 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001075 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001076 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001077}
1078
Alexey Bataeva63048e2015-03-23 06:18:07 +00001079static llvm::Value *emitCopyprivateCopyFunction(
1080 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> SrcExprs,
1081 ArrayRef<const Expr *> DstExprs, ArrayRef<const Expr *> AssignmentOps) {
1082 auto &C = CGM.getContext();
1083 // void copy_func(void *LHSArg, void *RHSArg);
1084 FunctionArgList Args;
1085 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1086 C.VoidPtrTy);
1087 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1088 C.VoidPtrTy);
1089 Args.push_back(&LHSArg);
1090 Args.push_back(&RHSArg);
1091 FunctionType::ExtInfo EI;
1092 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1093 C.VoidTy, Args, EI, /*isVariadic=*/false);
1094 auto *Fn = llvm::Function::Create(
1095 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1096 ".omp.copyprivate.copy_func", &CGM.getModule());
1097 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1098 CodeGenFunction CGF(CGM);
1099 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1100 // Dst = (void*[n])(LHSArg);
1101 // Src = (void*[n])(RHSArg);
1102 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1103 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1104 CGF.PointerAlignInBytes),
1105 ArgsType);
1106 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1107 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1108 CGF.PointerAlignInBytes),
1109 ArgsType);
1110 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1111 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1112 // ...
1113 // *(Typen*)Dst[n] = *(Typen*)Src[n];
1114 CodeGenFunction::OMPPrivateScope Scope(CGF);
1115 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
1116 Scope.addPrivate(
1117 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
1118 [&]() -> llvm::Value *{
1119 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
David Blaikie1ed728c2015-04-05 22:45:47 +00001120 CGF.Builder.CreateAlignedLoad(
1121 CGF.Builder.CreateStructGEP(nullptr, RHS, I),
1122 CGM.PointerAlignInBytes),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001123 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1124 });
1125 Scope.addPrivate(
1126 cast<VarDecl>(cast<DeclRefExpr>(DstExprs[I])->getDecl()),
1127 [&]() -> llvm::Value *{
1128 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
David Blaikie1ed728c2015-04-05 22:45:47 +00001129 CGF.Builder.CreateAlignedLoad(
1130 CGF.Builder.CreateStructGEP(nullptr, LHS, I),
1131 CGM.PointerAlignInBytes),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001132 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1133 });
1134 }
1135 Scope.Privatize();
1136 for (auto *E : AssignmentOps) {
1137 CGF.EmitIgnoredExpr(E);
1138 }
1139 Scope.ForceCleanup();
1140 CGF.FinishFunction();
1141 return Fn;
1142}
1143
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001144void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001145 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001146 SourceLocation Loc,
1147 ArrayRef<const Expr *> CopyprivateVars,
1148 ArrayRef<const Expr *> SrcExprs,
1149 ArrayRef<const Expr *> DstExprs,
1150 ArrayRef<const Expr *> AssignmentOps) {
1151 assert(CopyprivateVars.size() == SrcExprs.size() &&
1152 CopyprivateVars.size() == DstExprs.size() &&
1153 CopyprivateVars.size() == AssignmentOps.size());
1154 auto &C = CGM.getContext();
1155 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001156 // if(__kmpc_single(ident_t *, gtid)) {
1157 // SingleOpGen();
1158 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001159 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001160 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001161 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1162 // <copy_func>, did_it);
1163
1164 llvm::AllocaInst *DidIt = nullptr;
1165 if (!CopyprivateVars.empty()) {
1166 // int32 did_it = 0;
1167 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1168 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
1169 CGF.InitTempAlloca(DidIt, CGF.Builder.getInt32(0));
1170 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001171 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001172 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001173 auto *IsSingle =
1174 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001175 emitIfStmt(CGF, IsSingle, [&](CodeGenFunction &CGF) -> void {
1176 CodeGenFunction::RunCleanupsScope Scope(CGF);
1177 SingleOpGen(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001178 if (DidIt) {
1179 // did_it = 1;
1180 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1181 DidIt->getAlignment());
1182 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001183 // Build a call to __kmpc_end_single.
1184 // OpenMP [1.2.2 OpenMP Language Terminology]
1185 // For C/C++, an executable statement, possibly compound, with a single
1186 // entry at the top and a single exit at the bottom, or an OpenMP construct.
1187 // * Access to the structured block must not be the result of a branch.
1188 // * The point of exit cannot be a branch out of the structured block.
1189 // * The point of entry must not be a call to setjmp().
1190 // * longjmp() and throw() must not violate the entry/exit criteria.
1191 // * An expression statement, iteration statement, selection statement, or
1192 // try block is considered to be a structured block if the corresponding
1193 // compound statement obtained by enclosing it in { and } would be a
1194 // structured block.
1195 // It is analyzed in Sema, so we can just call __kmpc_end_single() on
1196 // fallthrough rather than pushing a normal cleanup for it.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001197 CGF.EHStack.pushCleanup<CallEndCleanup>(
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001198 NormalAndEHCleanup, [Loc](CodeGenFunction &CGF) {
1199 llvm::Value *Args[] = {
1200 CGF.CGM.getOpenMPRuntime().emitUpdateLocation(CGF, Loc),
1201 CGF.CGM.getOpenMPRuntime().getThreadID(CGF, Loc)};
1202 CGF.EmitRuntimeCall(CGF.CGM.getOpenMPRuntime().createRuntimeFunction(
1203 OMPRTL__kmpc_end_single),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001204 Args);
1205 });
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001206 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001207 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1208 // <copy_func>, did_it);
1209 if (DidIt) {
1210 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1211 auto CopyprivateArrayTy =
1212 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1213 /*IndexTypeQuals=*/0);
1214 // Create a list of all private variables for copyprivate.
1215 auto *CopyprivateList =
1216 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1217 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001218 auto *Elem = CGF.Builder.CreateStructGEP(
1219 CopyprivateList->getAllocatedType(), CopyprivateList, I);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001220 CGF.Builder.CreateAlignedStore(
1221 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1222 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1223 Elem, CGM.PointerAlignInBytes);
1224 }
1225 // Build function that copies private values from single region to all other
1226 // threads in the corresponding parallel region.
1227 auto *CpyFn = emitCopyprivateCopyFunction(
1228 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
1229 SrcExprs, DstExprs, AssignmentOps);
1230 auto *BufSize = CGF.Builder.getInt32(
1231 C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
1232 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1233 CGF.VoidPtrTy);
1234 auto *DidItVal =
1235 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1236 llvm::Value *Args[] = {
1237 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1238 getThreadID(CGF, Loc), // i32 <gtid>
1239 BufSize, // i32 <buf_size>
1240 CL, // void *<copyprivate list>
1241 CpyFn, // void (*) (void *, void *) <copy_func>
1242 DidItVal // i32 did_it
1243 };
1244 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1245 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001246}
1247
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001248void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf2685682015-03-30 04:30:22 +00001249 OpenMPDirectiveKind Kind) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001250 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001251 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1252 if (Kind == OMPD_for) {
1253 Flags =
1254 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1255 } else if (Kind == OMPD_sections) {
1256 Flags = static_cast<OpenMPLocationFlags>(Flags |
1257 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1258 } else if (Kind == OMPD_single) {
1259 Flags =
1260 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1261 } else if (Kind == OMPD_barrier) {
1262 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1263 } else {
1264 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1265 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001266 // Build call __kmpc_cancel_barrier(loc, thread_id);
1267 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1268 // one provides the same functionality and adds initial support for
1269 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1270 // is provided default by the runtime library so it safe to make such
1271 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001272 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1273 getThreadID(CGF, Loc)};
1274 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001275}
1276
Alexander Musmanc6388682014-12-15 07:07:06 +00001277/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1278/// the enum sched_type in kmp.h).
1279enum OpenMPSchedType {
1280 /// \brief Lower bound for default (unordered) versions.
1281 OMP_sch_lower = 32,
1282 OMP_sch_static_chunked = 33,
1283 OMP_sch_static = 34,
1284 OMP_sch_dynamic_chunked = 35,
1285 OMP_sch_guided_chunked = 36,
1286 OMP_sch_runtime = 37,
1287 OMP_sch_auto = 38,
1288 /// \brief Lower bound for 'ordered' versions.
1289 OMP_ord_lower = 64,
1290 /// \brief Lower bound for 'nomerge' versions.
1291 OMP_nm_lower = 160,
1292};
1293
1294/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1295static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
1296 bool Chunked) {
1297 switch (ScheduleKind) {
1298 case OMPC_SCHEDULE_static:
1299 return Chunked ? OMP_sch_static_chunked : OMP_sch_static;
1300 case OMPC_SCHEDULE_dynamic:
1301 return OMP_sch_dynamic_chunked;
1302 case OMPC_SCHEDULE_guided:
1303 return OMP_sch_guided_chunked;
1304 case OMPC_SCHEDULE_auto:
1305 return OMP_sch_auto;
1306 case OMPC_SCHEDULE_runtime:
1307 return OMP_sch_runtime;
1308 case OMPC_SCHEDULE_unknown:
1309 assert(!Chunked && "chunk was specified but schedule kind not known");
1310 return OMP_sch_static;
1311 }
1312 llvm_unreachable("Unexpected runtime schedule");
1313}
1314
1315bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1316 bool Chunked) const {
1317 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
1318 return Schedule == OMP_sch_static;
1319}
1320
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001321bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
1322 auto Schedule = getRuntimeSchedule(ScheduleKind, /* Chunked */ false);
1323 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1324 return Schedule != OMP_sch_static;
1325}
1326
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001327void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1328 OpenMPScheduleClauseKind ScheduleKind,
1329 unsigned IVSize, bool IVSigned,
1330 llvm::Value *IL, llvm::Value *LB,
1331 llvm::Value *UB, llvm::Value *ST,
1332 llvm::Value *Chunk) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001333 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunk != nullptr);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001334 if (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked) {
1335 // Call __kmpc_dispatch_init(
1336 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1337 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1338 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001339
Alexander Musman92bdaab2015-03-12 13:37:50 +00001340 // If the Chunk was not specified in the clause - use default value 1.
1341 if (Chunk == nullptr)
1342 Chunk = CGF.Builder.getIntN(IVSize, 1);
1343 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1344 getThreadID(CGF, Loc),
1345 CGF.Builder.getInt32(Schedule), // Schedule type
1346 CGF.Builder.getIntN(IVSize, 0), // Lower
1347 UB, // Upper
1348 CGF.Builder.getIntN(IVSize, 1), // Stride
1349 Chunk // Chunk
1350 };
1351 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1352 } else {
1353 // Call __kmpc_for_static_init(
1354 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1355 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1356 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1357 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1358 if (Chunk == nullptr) {
1359 assert(Schedule == OMP_sch_static &&
1360 "expected static non-chunked schedule");
1361 // If the Chunk was not specified in the clause - use default value 1.
1362 Chunk = CGF.Builder.getIntN(IVSize, 1);
1363 } else
1364 assert(Schedule == OMP_sch_static_chunked &&
1365 "expected static chunked schedule");
1366 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1367 getThreadID(CGF, Loc),
1368 CGF.Builder.getInt32(Schedule), // Schedule type
1369 IL, // &isLastIter
1370 LB, // &LB
1371 UB, // &UB
1372 ST, // &Stride
1373 CGF.Builder.getIntN(IVSize, 1), // Incr
1374 Chunk // Chunk
1375 };
Alexander Musman21212e42015-03-13 10:38:23 +00001376 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001377 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001378}
1379
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001380void CGOpenMPRuntime::emitForFinish(CodeGenFunction &CGF, SourceLocation Loc,
1381 OpenMPScheduleClauseKind ScheduleKind) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001382 assert((ScheduleKind == OMPC_SCHEDULE_static ||
1383 ScheduleKind == OMPC_SCHEDULE_unknown) &&
1384 "Non-static schedule kinds are not yet implemented");
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001385 (void)ScheduleKind;
Alexander Musmanc6388682014-12-15 07:07:06 +00001386 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001387 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1388 getThreadID(CGF, Loc)};
1389 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1390 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001391}
1392
Alexander Musman92bdaab2015-03-12 13:37:50 +00001393llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1394 SourceLocation Loc, unsigned IVSize,
1395 bool IVSigned, llvm::Value *IL,
1396 llvm::Value *LB, llvm::Value *UB,
1397 llvm::Value *ST) {
1398 // Call __kmpc_dispatch_next(
1399 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1400 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1401 // kmp_int[32|64] *p_stride);
1402 llvm::Value *Args[] = {
1403 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1404 IL, // &isLastIter
1405 LB, // &Lower
1406 UB, // &Upper
1407 ST // &Stride
1408 };
1409 llvm::Value *Call =
1410 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1411 return CGF.EmitScalarConversion(
1412 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1413 CGF.getContext().BoolTy);
1414}
1415
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001416void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1417 llvm::Value *NumThreads,
1418 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001419 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1420 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001421 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001422 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001423 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1424 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001425}
1426
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001427void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1428 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001429 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001430 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1431 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001432}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001433
Alexey Bataev62b63b12015-03-10 07:28:44 +00001434namespace {
1435/// \brief Indexes of fields for type kmp_task_t.
1436enum KmpTaskTFields {
1437 /// \brief List of shared variables.
1438 KmpTaskTShareds,
1439 /// \brief Task routine.
1440 KmpTaskTRoutine,
1441 /// \brief Partition id for the untied tasks.
1442 KmpTaskTPartId,
1443 /// \brief Function with call of destructors for private variables.
1444 KmpTaskTDestructors,
1445};
1446} // namespace
1447
1448void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1449 if (!KmpRoutineEntryPtrTy) {
1450 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1451 auto &C = CGM.getContext();
1452 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1453 FunctionProtoType::ExtProtoInfo EPI;
1454 KmpRoutineEntryPtrQTy = C.getPointerType(
1455 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1456 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1457 }
1458}
1459
1460static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1461 QualType FieldTy) {
1462 auto *Field = FieldDecl::Create(
1463 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1464 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1465 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1466 Field->setAccess(AS_public);
1467 DC->addDecl(Field);
1468}
1469
1470static QualType createKmpTaskTRecordDecl(CodeGenModule &CGM,
1471 QualType KmpInt32Ty,
1472 QualType KmpRoutineEntryPointerQTy) {
1473 auto &C = CGM.getContext();
1474 // Build struct kmp_task_t {
1475 // void * shareds;
1476 // kmp_routine_entry_t routine;
1477 // kmp_int32 part_id;
1478 // kmp_routine_entry_t destructors;
1479 // /* private vars */
1480 // };
1481 auto *RD = C.buildImplicitRecord("kmp_task_t");
1482 RD->startDefinition();
1483 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1484 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1485 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1486 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1487 // TODO: add private fields.
1488 RD->completeDefinition();
1489 return C.getRecordType(RD);
1490}
1491
1492/// \brief Emit a proxy function which accepts kmp_task_t as the second
1493/// argument.
1494/// \code
1495/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1496/// TaskFunction(gtid, tt->part_id, tt->shareds);
1497/// return 0;
1498/// }
1499/// \endcode
1500static llvm::Value *
1501emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
1502 QualType KmpInt32Ty, QualType KmpTaskTPtrQTy,
David Blaikie2e804282015-04-05 22:47:07 +00001503 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1504 llvm::Type *KmpTaskTTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001505 auto &C = CGM.getContext();
1506 FunctionArgList Args;
1507 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1508 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
1509 /*Id=*/nullptr, KmpTaskTPtrQTy);
1510 Args.push_back(&GtidArg);
1511 Args.push_back(&TaskTypeArg);
1512 FunctionType::ExtInfo Info;
1513 auto &TaskEntryFnInfo =
1514 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1515 /*isVariadic=*/false);
1516 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1517 auto *TaskEntry =
1518 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1519 ".omp_task_entry.", &CGM.getModule());
1520 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1521 CodeGenFunction CGF(CGM);
1522 CGF.disableDebugInfo();
1523 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1524
1525 // TaskFunction(gtid, tt->part_id, tt->shareds);
1526 auto *GtidParam = CGF.EmitLoadOfScalar(
1527 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1528 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
1529 auto TaskTypeArgAddr = CGF.EmitLoadOfScalar(
1530 CGF.GetAddrOfLocalVar(&TaskTypeArg), /*Volatile=*/false,
1531 CGM.PointerAlignInBytes, KmpTaskTPtrQTy, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001532 auto *PartidPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001533 /*Idx=*/KmpTaskTPartId);
1534 auto *PartidParam = CGF.EmitLoadOfScalar(
1535 PartidPtr, /*Volatile=*/false,
1536 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001537 auto *SharedsPtr = CGF.Builder.CreateStructGEP(KmpTaskTTy, TaskTypeArgAddr,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001538 /*Idx=*/KmpTaskTShareds);
1539 auto *SharedsParam =
1540 CGF.EmitLoadOfScalar(SharedsPtr, /*Volatile=*/false,
1541 CGM.PointerAlignInBytes, C.VoidPtrTy, Loc);
1542 llvm::Value *CallArgs[] = {
1543 GtidParam, PartidParam,
1544 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1545 SharedsParam, CGF.ConvertTypeForMem(SharedsPtrTy))};
1546 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1547 CGF.EmitStoreThroughLValue(
1548 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1549 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1550 CGF.FinishFunction();
1551 return TaskEntry;
1552}
1553
1554void CGOpenMPRuntime::emitTaskCall(
1555 CodeGenFunction &CGF, SourceLocation Loc, bool Tied,
1556 llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
1557 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds) {
1558 auto &C = CGM.getContext();
1559 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1560 // Build type kmp_routine_entry_t (if not built yet).
1561 emitKmpRoutineEntryT(KmpInt32Ty);
1562 // Build particular struct kmp_task_t for the given task.
1563 auto KmpTaskQTy =
1564 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy);
1565 QualType KmpTaskTPtrQTy = C.getPointerType(KmpTaskQTy);
David Blaikie1ed728c2015-04-05 22:45:47 +00001566 auto *KmpTaskTTy = CGF.ConvertType(KmpTaskQTy);
1567 auto *KmpTaskTPtrTy = KmpTaskTTy->getPointerTo();
Alexey Bataev62b63b12015-03-10 07:28:44 +00001568 auto KmpTaskTySize = CGM.getSize(C.getTypeSizeInChars(KmpTaskQTy));
1569 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
1570
1571 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
1572 // kmp_task_t *tt);
David Blaikie1ed728c2015-04-05 22:45:47 +00001573 auto *TaskEntry =
1574 emitProxyTaskFunction(CGM, Loc, KmpInt32Ty, KmpTaskTPtrQTy, SharedsPtrTy,
1575 TaskFunction, KmpTaskTTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001576
1577 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1578 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1579 // kmp_routine_entry_t *task_entry);
1580 // Task flags. Format is taken from
1581 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
1582 // description of kmp_tasking_flags struct.
1583 const unsigned TiedFlag = 0x1;
1584 const unsigned FinalFlag = 0x2;
1585 unsigned Flags = Tied ? TiedFlag : 0;
1586 auto *TaskFlags =
1587 Final.getPointer()
1588 ? CGF.Builder.CreateSelect(Final.getPointer(),
1589 CGF.Builder.getInt32(FinalFlag),
1590 CGF.Builder.getInt32(/*C=*/0))
1591 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
1592 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
1593 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
1594 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
1595 getThreadID(CGF, Loc), TaskFlags, KmpTaskTySize,
1596 CGM.getSize(SharedsSize),
1597 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1598 TaskEntry, KmpRoutineEntryPtrTy)};
1599 auto *NewTask = CGF.EmitRuntimeCall(
1600 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
1601 auto *NewTaskNewTaskTTy =
1602 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NewTask, KmpTaskTPtrTy);
1603 // Fill the data in the resulting kmp_task_t record.
1604 // Copy shareds if there are any.
1605 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty())
1606 CGF.EmitAggregateCopy(
1607 CGF.EmitLoadOfScalar(
David Blaikie1ed728c2015-04-05 22:45:47 +00001608 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001609 /*Idx=*/KmpTaskTShareds),
1610 /*Volatile=*/false, CGM.PointerAlignInBytes, SharedsPtrTy, Loc),
1611 Shareds, SharedsTy);
1612 // TODO: generate function with destructors for privates.
1613 // Provide pointer to function with destructors for privates.
1614 CGF.Builder.CreateAlignedStore(
1615 llvm::ConstantPointerNull::get(
1616 cast<llvm::PointerType>(KmpRoutineEntryPtrTy)),
David Blaikie1ed728c2015-04-05 22:45:47 +00001617 CGF.Builder.CreateStructGEP(KmpTaskTTy, NewTaskNewTaskTTy,
Alexey Bataev62b63b12015-03-10 07:28:44 +00001618 /*Idx=*/KmpTaskTDestructors),
1619 CGM.PointerAlignInBytes);
1620
1621 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
1622 // libcall.
1623 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1624 // *new_task);
1625 llvm::Value *TaskArgs[] = {emitUpdateLocation(CGF, Loc),
1626 getThreadID(CGF, Loc), NewTask};
1627 // TODO: add check for untied tasks.
1628 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1629}
1630
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001631void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
1632 const RegionCodeGenTy &CodeGen) {
1633 InlinedOpenMPRegionRAII Region(CGF, CodeGen);
1634 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001635}
1636