blob: f9553a2203c707298de7c3c4c889f2ccebe2f083 [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.
Alexander Kornienko34eb2072015-04-11 02:00:23 +000090 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000091
Alexey Bataev18095712014-10-10 12:19:54 +000092 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +000093 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +000094
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000095 static bool classof(const CGCapturedStmtInfo *Info) {
96 return CGOpenMPRegionInfo::classof(Info) &&
97 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
98 ParallelOutlinedRegion;
99 }
100
Alexey Bataev18095712014-10-10 12:19:54 +0000101private:
102 /// \brief A variable or parameter storing global thread id for OpenMP
103 /// constructs.
104 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000105};
106
Alexey Bataev62b63b12015-03-10 07:28:44 +0000107/// \brief API for captured statement code generation in OpenMP constructs.
108class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
109public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000110 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000111 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000112 const RegionCodeGenTy &CodeGen)
113 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen),
114 ThreadIDVar(ThreadIDVar) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000115 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
116 }
117 /// \brief Get a variable or parameter for storing global thread id
118 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000119 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000120
121 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000122 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000123
Alexey Bataev62b63b12015-03-10 07:28:44 +0000124 /// \brief Get the name of the capture helper.
125 StringRef getHelperName() const override { return ".omp_outlined."; }
126
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000127 static bool classof(const CGCapturedStmtInfo *Info) {
128 return CGOpenMPRegionInfo::classof(Info) &&
129 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
130 TaskOutlinedRegion;
131 }
132
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133private:
134 /// \brief A variable or parameter storing global thread id for OpenMP
135 /// constructs.
136 const VarDecl *ThreadIDVar;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000137};
138
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000139/// \brief API for inlined captured statement code generation in OpenMP
140/// constructs.
141class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
142public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000143 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
144 const RegionCodeGenTy &CodeGen)
145 : CGOpenMPRegionInfo(InlinedRegion, CodeGen), OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000146 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
147 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000148 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000149 if (OuterRegionInfo)
150 return OuterRegionInfo->getContextValue();
151 llvm_unreachable("No context value for inlined OpenMP region");
152 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000153 virtual void setContextValue(llvm::Value *V) override {
154 if (OuterRegionInfo) {
155 OuterRegionInfo->setContextValue(V);
156 return;
157 }
158 llvm_unreachable("No context value for inlined OpenMP region");
159 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000160 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000161 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000162 if (OuterRegionInfo)
163 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000164 // If there is no outer outlined region,no need to lookup in a list of
165 // captured variables, we can use the original one.
166 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000167 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000168 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000169 if (OuterRegionInfo)
170 return OuterRegionInfo->getThisFieldDecl();
171 return nullptr;
172 }
173 /// \brief Get a variable or parameter for storing global thread id
174 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000175 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000176 if (OuterRegionInfo)
177 return OuterRegionInfo->getThreadIDVariable();
178 return nullptr;
179 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000180
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000181 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000182 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000183 if (auto *OuterRegionInfo = getOldCSI())
184 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000185 llvm_unreachable("No helper name for inlined OpenMP construct");
186 }
187
188 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
189
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000190 static bool classof(const CGCapturedStmtInfo *Info) {
191 return CGOpenMPRegionInfo::classof(Info) &&
192 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
193 }
194
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000195private:
196 /// \brief CodeGen info about outer OpenMP region.
197 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
198 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000199};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000200
201/// \brief RAII for emitting code of OpenMP constructs.
202class InlinedOpenMPRegionRAII {
203 CodeGenFunction &CGF;
204
205public:
206 /// \brief Constructs region for combined constructs.
207 /// \param CodeGen Code generation sequence for combined directives. Includes
208 /// a list of functions used for code generation of implicitly inlined
209 /// regions.
210 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen)
211 : CGF(CGF) {
212 // Start emission for the construct.
213 CGF.CapturedStmtInfo =
214 new CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, CodeGen);
215 }
216 ~InlinedOpenMPRegionRAII() {
217 // Restore original CapturedStmtInfo only if we're done with code emission.
218 auto *OldCSI =
219 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
220 delete CGF.CapturedStmtInfo;
221 CGF.CapturedStmtInfo = OldCSI;
222 }
223};
224
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000225} // namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000226
227LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
228 return CGF.MakeNaturalAlignAddrLValue(
Alexey Bataev62b63b12015-03-10 07:28:44 +0000229 CGF.Builder.CreateAlignedLoad(
230 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
231 CGF.PointerAlignInBytes),
232 getThreadIDVariable()
233 ->getType()
234 ->castAs<PointerType>()
235 ->getPointeeType());
Alexey Bataev18095712014-10-10 12:19:54 +0000236}
237
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
239 // 1.2.2 OpenMP Language Terminology
240 // Structured block - An executable statement with a single entry at the
241 // top and a single exit at the bottom.
242 // The point of exit cannot be a branch out of the structured block.
243 // longjmp() and throw() must not violate the entry/exit criteria.
244 CGF.EHStack.pushTerminate();
245 {
246 CodeGenFunction::RunCleanupsScope Scope(CGF);
247 CodeGen(CGF);
248 }
249 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000250}
251
Alexey Bataev62b63b12015-03-10 07:28:44 +0000252LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
253 CodeGenFunction &CGF) {
254 return CGF.MakeNaturalAlignAddrLValue(
255 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
256 getThreadIDVariable()->getType());
257}
258
Alexey Bataev9959db52014-05-06 10:08:46 +0000259CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataev62b63b12015-03-10 07:28:44 +0000260 : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000261 IdentTy = llvm::StructType::create(
262 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
263 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000264 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000265 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
Alexey Bataev23b69422014-06-18 07:08:49 +0000266 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
267 llvm::PointerType::getUnqual(CGM.Int32Ty)};
Alexey Bataev9959db52014-05-06 10:08:46 +0000268 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000269 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Alexey Bataev9959db52014-05-06 10:08:46 +0000270}
271
Alexey Bataev91797552015-03-18 04:13:55 +0000272void CGOpenMPRuntime::clear() {
273 InternalVars.clear();
274}
275
Alexey Bataev9959db52014-05-06 10:08:46 +0000276llvm::Value *
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277CGOpenMPRuntime::emitParallelOutlinedFunction(const OMPExecutableDirective &D,
278 const VarDecl *ThreadIDVar,
279 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000280 assert(ThreadIDVar->getType()->isPointerType() &&
281 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000282 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
283 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000284 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataevd157d472015-06-24 03:35:38 +0000285 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev18095712014-10-10 12:19:54 +0000286 return CGF.GenerateCapturedStmtFunction(*CS);
287}
288
289llvm::Value *
Alexey Bataev62b63b12015-03-10 07:28:44 +0000290CGOpenMPRuntime::emitTaskOutlinedFunction(const OMPExecutableDirective &D,
291 const VarDecl *ThreadIDVar,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000292 const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000293 assert(!ThreadIDVar->getType()->isPointerType() &&
294 "thread id variable must be of type kmp_int32 for tasks");
295 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
296 CodeGenFunction CGF(CGM, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000297 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen);
Alexey Bataevd157d472015-06-24 03:35:38 +0000298 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000299 return CGF.GenerateCapturedStmtFunction(*CS);
300}
301
302llvm::Value *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000303CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000304 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000305 if (!Entry) {
306 if (!DefaultOpenMPPSource) {
307 // Initialize default location for psource field of ident_t structure of
308 // all ident_t objects. Format is ";file;function;line;column;;".
309 // Taken from
310 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
311 DefaultOpenMPPSource =
312 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
313 DefaultOpenMPPSource =
314 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
315 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000316 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
317 CGM.getModule(), IdentTy, /*isConstant*/ true,
318 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000319 DefaultOpenMPLocation->setUnnamedAddr(true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000320
321 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000322 llvm::Constant *Values[] = {Zero,
323 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
324 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000325 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
326 DefaultOpenMPLocation->setInitializer(Init);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000327 OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000328 return DefaultOpenMPLocation;
329 }
330 return Entry;
331}
332
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000333llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
334 SourceLocation Loc,
335 OpenMPLocationFlags Flags) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000336 // If no debug info is generated - return global default location.
337 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
338 Loc.isInvalid())
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000339 return getOrCreateDefaultLocation(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000340
341 assert(CGF.CurFn && "No function in current CodeGenFunction.");
342
Alexey Bataev9959db52014-05-06 10:08:46 +0000343 llvm::Value *LocValue = nullptr;
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000344 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
345 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataev18095712014-10-10 12:19:54 +0000346 LocValue = I->second.DebugLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +0000347 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
348 // GetOpenMPThreadID was called before this routine.
349 if (LocValue == nullptr) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000350 // Generate "ident_t .kmpc_loc.addr;"
351 llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
Alexey Bataev9959db52014-05-06 10:08:46 +0000352 AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
Alexey Bataev18095712014-10-10 12:19:54 +0000353 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
354 Elem.second.DebugLoc = AI;
Alexey Bataev9959db52014-05-06 10:08:46 +0000355 LocValue = AI;
356
357 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
358 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000359 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataev9959db52014-05-06 10:08:46 +0000360 llvm::ConstantExpr::getSizeOf(IdentTy),
361 CGM.PointerAlignInBytes);
362 }
363
364 // char **psource = &.kmpc_loc_<flags>.addr.psource;
David Blaikie1ed728c2015-04-05 22:45:47 +0000365 auto *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(IdentTy, LocValue, 0,
366 IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000367
Alexey Bataevf002aca2014-05-30 05:48:40 +0000368 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
369 if (OMPDebugLoc == nullptr) {
370 SmallString<128> Buffer2;
371 llvm::raw_svector_ostream OS2(Buffer2);
372 // Build debug location
373 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
374 OS2 << ";" << PLoc.getFilename() << ";";
375 if (const FunctionDecl *FD =
376 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
377 OS2 << FD->getQualifiedNameAsString();
378 }
379 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
380 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
381 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000382 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000383 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000384 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
385
Alexey Bataev9959db52014-05-06 10:08:46 +0000386 return LocValue;
387}
388
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000389llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
390 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000391 assert(CGF.CurFn && "No function in current CodeGenFunction.");
392
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000393 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000394 // Check whether we've already cached a load of the thread id in this
395 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000396 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000397 if (I != OpenMPLocThreadIDMap.end()) {
398 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000399 if (ThreadID != nullptr)
400 return ThreadID;
401 }
402 if (auto OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000403 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000404 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000405 // Check if this an outlined function with thread id passed as argument.
406 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000407 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
408 // If value loaded in entry block, cache it and use it everywhere in
409 // function.
410 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
411 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
412 Elem.second.ThreadID = ThreadID;
413 }
414 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000415 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000416 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000417
418 // This is not an outlined function region - need to call __kmpc_int32
419 // kmpc_global_thread_num(ident_t *loc).
420 // Generate thread id value and cache this value for use across the
421 // function.
422 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
423 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
424 ThreadID =
425 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
426 emitUpdateLocation(CGF, Loc));
427 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
428 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000429 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000430}
431
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000432void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000433 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +0000434 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
435 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataev9959db52014-05-06 10:08:46 +0000436}
437
438llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
439 return llvm::PointerType::getUnqual(IdentTy);
440}
441
442llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
443 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
444}
445
446llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000447CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000448 llvm::Constant *RTLFn = nullptr;
449 switch (Function) {
450 case OMPRTL__kmpc_fork_call: {
451 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
452 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +0000453 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
454 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000455 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000456 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +0000457 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
458 break;
459 }
460 case OMPRTL__kmpc_global_thread_num: {
461 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +0000462 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +0000463 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +0000464 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +0000465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
466 break;
467 }
Alexey Bataev97720002014-11-11 04:05:39 +0000468 case OMPRTL__kmpc_threadprivate_cached: {
469 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
470 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
471 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
472 CGM.VoidPtrTy, CGM.SizeTy,
473 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
474 llvm::FunctionType *FnTy =
475 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
476 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
477 break;
478 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000479 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000480 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
481 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000482 llvm::Type *TypeParams[] = {
483 getIdentTyPointerTy(), CGM.Int32Ty,
484 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
485 llvm::FunctionType *FnTy =
486 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
487 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
488 break;
489 }
Alexey Bataev97720002014-11-11 04:05:39 +0000490 case OMPRTL__kmpc_threadprivate_register: {
491 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
492 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
493 // typedef void *(*kmpc_ctor)(void *);
494 auto KmpcCtorTy =
495 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
496 /*isVarArg*/ false)->getPointerTo();
497 // typedef void *(*kmpc_cctor)(void *, void *);
498 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
499 auto KmpcCopyCtorTy =
500 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
501 /*isVarArg*/ false)->getPointerTo();
502 // typedef void (*kmpc_dtor)(void *);
503 auto KmpcDtorTy =
504 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
505 ->getPointerTo();
506 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
507 KmpcCopyCtorTy, KmpcDtorTy};
508 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
509 /*isVarArg*/ false);
510 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
511 break;
512 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000513 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +0000514 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
515 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000516 llvm::Type *TypeParams[] = {
517 getIdentTyPointerTy(), CGM.Int32Ty,
518 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
519 llvm::FunctionType *FnTy =
520 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
521 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
522 break;
523 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000524 case OMPRTL__kmpc_cancel_barrier: {
525 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
526 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000527 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
528 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +0000529 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
530 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000531 break;
532 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000533 case OMPRTL__kmpc_for_static_fini: {
534 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
535 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
536 llvm::FunctionType *FnTy =
537 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
538 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
539 break;
540 }
Alexey Bataevb2059782014-10-13 08:23:51 +0000541 case OMPRTL__kmpc_push_num_threads: {
542 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
543 // kmp_int32 num_threads)
544 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
545 CGM.Int32Ty};
546 llvm::FunctionType *FnTy =
547 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
548 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
549 break;
550 }
Alexey Bataevd74d0602014-10-13 06:02:40 +0000551 case OMPRTL__kmpc_serialized_parallel: {
552 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
553 // global_tid);
554 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
555 llvm::FunctionType *FnTy =
556 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
557 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
558 break;
559 }
560 case OMPRTL__kmpc_end_serialized_parallel: {
561 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
562 // global_tid);
563 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
564 llvm::FunctionType *FnTy =
565 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
566 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
567 break;
568 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000569 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000570 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000571 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
572 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +0000573 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +0000574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
575 break;
576 }
Alexey Bataev8d690652014-12-04 07:23:53 +0000577 case OMPRTL__kmpc_master: {
578 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
580 llvm::FunctionType *FnTy =
581 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
582 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
583 break;
584 }
585 case OMPRTL__kmpc_end_master: {
586 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
587 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
588 llvm::FunctionType *FnTy =
589 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
590 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
591 break;
592 }
Alexey Bataev9f797f32015-02-05 05:57:51 +0000593 case OMPRTL__kmpc_omp_taskyield: {
594 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
595 // int end_part);
596 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
597 llvm::FunctionType *FnTy =
598 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
599 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
600 break;
601 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +0000602 case OMPRTL__kmpc_single: {
603 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
604 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
605 llvm::FunctionType *FnTy =
606 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
607 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
608 break;
609 }
610 case OMPRTL__kmpc_end_single: {
611 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
612 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
613 llvm::FunctionType *FnTy =
614 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
615 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
616 break;
617 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000618 case OMPRTL__kmpc_omp_task_alloc: {
619 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
620 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
621 // kmp_routine_entry_t *task_entry);
622 assert(KmpRoutineEntryPtrTy != nullptr &&
623 "Type kmp_routine_entry_t must be created.");
624 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
625 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
626 // Return void * and then cast to particular kmp_task_t type.
627 llvm::FunctionType *FnTy =
628 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
629 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
630 break;
631 }
632 case OMPRTL__kmpc_omp_task: {
633 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
634 // *new_task);
635 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
636 CGM.VoidPtrTy};
637 llvm::FunctionType *FnTy =
638 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
639 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
640 break;
641 }
Alexey Bataeva63048e2015-03-23 06:18:07 +0000642 case OMPRTL__kmpc_copyprivate: {
643 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +0000644 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +0000645 // kmp_int32 didit);
646 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
647 auto *CpyFnTy =
648 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +0000649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +0000650 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
651 CGM.Int32Ty};
652 llvm::FunctionType *FnTy =
653 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
654 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
655 break;
656 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000657 case OMPRTL__kmpc_reduce: {
658 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
659 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
660 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
661 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
662 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
663 /*isVarArg=*/false);
664 llvm::Type *TypeParams[] = {
665 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
666 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
667 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
668 llvm::FunctionType *FnTy =
669 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
670 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
671 break;
672 }
673 case OMPRTL__kmpc_reduce_nowait: {
674 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
675 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
676 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
677 // *lck);
678 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
679 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
680 /*isVarArg=*/false);
681 llvm::Type *TypeParams[] = {
682 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
683 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
684 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
685 llvm::FunctionType *FnTy =
686 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
687 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
688 break;
689 }
690 case OMPRTL__kmpc_end_reduce: {
691 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
692 // kmp_critical_name *lck);
693 llvm::Type *TypeParams[] = {
694 getIdentTyPointerTy(), CGM.Int32Ty,
695 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
696 llvm::FunctionType *FnTy =
697 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
698 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
699 break;
700 }
701 case OMPRTL__kmpc_end_reduce_nowait: {
702 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
703 // kmp_critical_name *lck);
704 llvm::Type *TypeParams[] = {
705 getIdentTyPointerTy(), CGM.Int32Ty,
706 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
707 llvm::FunctionType *FnTy =
708 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
709 RTLFn =
710 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
711 break;
712 }
Alexey Bataev1d677132015-04-22 13:57:31 +0000713 case OMPRTL__kmpc_omp_task_begin_if0: {
714 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
715 // *new_task);
716 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
717 CGM.VoidPtrTy};
718 llvm::FunctionType *FnTy =
719 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
720 RTLFn =
721 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
722 break;
723 }
724 case OMPRTL__kmpc_omp_task_complete_if0: {
725 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
726 // *new_task);
727 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
728 CGM.VoidPtrTy};
729 llvm::FunctionType *FnTy =
730 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
731 RTLFn = CGM.CreateRuntimeFunction(FnTy,
732 /*Name=*/"__kmpc_omp_task_complete_if0");
733 break;
734 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000735 case OMPRTL__kmpc_ordered: {
736 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
737 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
738 llvm::FunctionType *FnTy =
739 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
740 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
741 break;
742 }
743 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000744 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000745 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
746 llvm::FunctionType *FnTy =
747 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
748 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
749 break;
750 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +0000751 case OMPRTL__kmpc_omp_taskwait: {
752 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
753 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
754 llvm::FunctionType *FnTy =
755 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
756 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
757 break;
758 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +0000759 case OMPRTL__kmpc_taskgroup: {
760 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
761 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
762 llvm::FunctionType *FnTy =
763 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
764 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
765 break;
766 }
767 case OMPRTL__kmpc_end_taskgroup: {
768 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
769 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
770 llvm::FunctionType *FnTy =
771 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
772 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
773 break;
774 }
Alexey Bataev7f210c62015-06-18 13:40:03 +0000775 case OMPRTL__kmpc_push_proc_bind: {
776 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
777 // int proc_bind)
778 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
779 llvm::FunctionType *FnTy =
780 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
781 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
782 break;
783 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +0000784 case OMPRTL__kmpc_omp_task_with_deps: {
785 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
786 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
787 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
788 llvm::Type *TypeParams[] = {
789 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
790 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
791 llvm::FunctionType *FnTy =
792 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
793 RTLFn =
794 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
795 break;
796 }
797 case OMPRTL__kmpc_omp_wait_deps: {
798 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
799 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
800 // kmp_depend_info_t *noalias_dep_list);
801 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
802 CGM.Int32Ty, CGM.VoidPtrTy,
803 CGM.Int32Ty, CGM.VoidPtrTy};
804 llvm::FunctionType *FnTy =
805 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
806 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
807 break;
808 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000809 }
810 return RTLFn;
811}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000812
Alexander Musman21212e42015-03-13 10:38:23 +0000813llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
814 bool IVSigned) {
815 assert((IVSize == 32 || IVSize == 64) &&
816 "IV size is not compatible with the omp runtime");
817 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
818 : "__kmpc_for_static_init_4u")
819 : (IVSigned ? "__kmpc_for_static_init_8"
820 : "__kmpc_for_static_init_8u");
821 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
822 auto PtrTy = llvm::PointerType::getUnqual(ITy);
823 llvm::Type *TypeParams[] = {
824 getIdentTyPointerTy(), // loc
825 CGM.Int32Ty, // tid
826 CGM.Int32Ty, // schedtype
827 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
828 PtrTy, // p_lower
829 PtrTy, // p_upper
830 PtrTy, // p_stride
831 ITy, // incr
832 ITy // chunk
833 };
834 llvm::FunctionType *FnTy =
835 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
836 return CGM.CreateRuntimeFunction(FnTy, Name);
837}
838
Alexander Musman92bdaab2015-03-12 13:37:50 +0000839llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
840 bool IVSigned) {
841 assert((IVSize == 32 || IVSize == 64) &&
842 "IV size is not compatible with the omp runtime");
843 auto Name =
844 IVSize == 32
845 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
846 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
847 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
848 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
849 CGM.Int32Ty, // tid
850 CGM.Int32Ty, // schedtype
851 ITy, // lower
852 ITy, // upper
853 ITy, // stride
854 ITy // chunk
855 };
856 llvm::FunctionType *FnTy =
857 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
858 return CGM.CreateRuntimeFunction(FnTy, Name);
859}
860
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000861llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
862 bool IVSigned) {
863 assert((IVSize == 32 || IVSize == 64) &&
864 "IV size is not compatible with the omp runtime");
865 auto Name =
866 IVSize == 32
867 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
868 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
869 llvm::Type *TypeParams[] = {
870 getIdentTyPointerTy(), // loc
871 CGM.Int32Ty, // tid
872 };
873 llvm::FunctionType *FnTy =
874 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
875 return CGM.CreateRuntimeFunction(FnTy, Name);
876}
877
Alexander Musman92bdaab2015-03-12 13:37:50 +0000878llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
879 bool IVSigned) {
880 assert((IVSize == 32 || IVSize == 64) &&
881 "IV size is not compatible with the omp runtime");
882 auto Name =
883 IVSize == 32
884 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
885 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
886 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
887 auto PtrTy = llvm::PointerType::getUnqual(ITy);
888 llvm::Type *TypeParams[] = {
889 getIdentTyPointerTy(), // loc
890 CGM.Int32Ty, // tid
891 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
892 PtrTy, // p_lower
893 PtrTy, // p_upper
894 PtrTy // p_stride
895 };
896 llvm::FunctionType *FnTy =
897 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
898 return CGM.CreateRuntimeFunction(FnTy, Name);
899}
900
Alexey Bataev97720002014-11-11 04:05:39 +0000901llvm::Constant *
902CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
903 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000904 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000905 Twine(CGM.getMangledName(VD)) + ".cache.");
906}
907
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000908llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
909 const VarDecl *VD,
910 llvm::Value *VDAddr,
911 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000912 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000913 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000914 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
915 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
916 getOrCreateThreadPrivateCache(VD)};
917 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000918 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000919}
920
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000921void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000922 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
923 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
924 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
925 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000926 auto OMPLoc = emitUpdateLocation(CGF, Loc);
927 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000928 OMPLoc);
929 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
930 // to register constructor/destructor for variable.
931 llvm::Value *Args[] = {OMPLoc,
932 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
933 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000934 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000935 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000936}
937
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000938llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000939 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
940 bool PerformInit, CodeGenFunction *CGF) {
941 VD = VD->getDefinition(CGM.getContext());
942 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
943 ThreadPrivateWithDefinition.insert(VD);
944 QualType ASTTy = VD->getType();
945
946 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
947 auto Init = VD->getAnyInitializer();
948 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
949 // Generate function that re-emits the declaration's initializer into the
950 // threadprivate copy of the variable VD
951 CodeGenFunction CtorCGF(CGM);
952 FunctionArgList Args;
953 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
954 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
955 Args.push_back(&Dst);
956
957 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
958 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
959 /*isVariadic=*/false);
960 auto FTy = CGM.getTypes().GetFunctionType(FI);
961 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
962 FTy, ".__kmpc_global_ctor_.", Loc);
963 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
964 Args, SourceLocation());
965 auto ArgVal = CtorCGF.EmitLoadOfScalar(
966 CtorCGF.GetAddrOfLocalVar(&Dst),
967 /*Volatile=*/false, CGM.PointerAlignInBytes,
968 CGM.getContext().VoidPtrTy, Dst.getLocation());
969 auto Arg = CtorCGF.Builder.CreatePointerCast(
970 ArgVal,
971 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
972 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
973 /*IsInitializer=*/true);
974 ArgVal = CtorCGF.EmitLoadOfScalar(
975 CtorCGF.GetAddrOfLocalVar(&Dst),
976 /*Volatile=*/false, CGM.PointerAlignInBytes,
977 CGM.getContext().VoidPtrTy, Dst.getLocation());
978 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
979 CtorCGF.FinishFunction();
980 Ctor = Fn;
981 }
982 if (VD->getType().isDestructedType() != QualType::DK_none) {
983 // Generate function that emits destructor call for the threadprivate copy
984 // of the variable VD
985 CodeGenFunction DtorCGF(CGM);
986 FunctionArgList Args;
987 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
988 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
989 Args.push_back(&Dst);
990
991 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
992 CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
993 /*isVariadic=*/false);
994 auto FTy = CGM.getTypes().GetFunctionType(FI);
995 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
996 FTy, ".__kmpc_global_dtor_.", Loc);
997 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
998 SourceLocation());
999 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1000 DtorCGF.GetAddrOfLocalVar(&Dst),
1001 /*Volatile=*/false, CGM.PointerAlignInBytes,
1002 CGM.getContext().VoidPtrTy, Dst.getLocation());
1003 DtorCGF.emitDestroy(ArgVal, ASTTy,
1004 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1005 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1006 DtorCGF.FinishFunction();
1007 Dtor = Fn;
1008 }
1009 // Do not emit init function if it is not required.
1010 if (!Ctor && !Dtor)
1011 return nullptr;
1012
1013 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1014 auto CopyCtorTy =
1015 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1016 /*isVarArg=*/false)->getPointerTo();
1017 // Copying constructor for the threadprivate variable.
1018 // Must be NULL - reserved by runtime, but currently it requires that this
1019 // parameter is always NULL. Otherwise it fires assertion.
1020 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1021 if (Ctor == nullptr) {
1022 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1023 /*isVarArg=*/false)->getPointerTo();
1024 Ctor = llvm::Constant::getNullValue(CtorTy);
1025 }
1026 if (Dtor == nullptr) {
1027 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1028 /*isVarArg=*/false)->getPointerTo();
1029 Dtor = llvm::Constant::getNullValue(DtorTy);
1030 }
1031 if (!CGF) {
1032 auto InitFunctionTy =
1033 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1034 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1035 InitFunctionTy, ".__omp_threadprivate_init_.");
1036 CodeGenFunction InitCGF(CGM);
1037 FunctionArgList ArgList;
1038 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1039 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1040 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001041 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001042 InitCGF.FinishFunction();
1043 return InitFunction;
1044 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001045 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001046 }
1047 return nullptr;
1048}
1049
Alexey Bataev1d677132015-04-22 13:57:31 +00001050/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1051/// function. Here is the logic:
1052/// if (Cond) {
1053/// ThenGen();
1054/// } else {
1055/// ElseGen();
1056/// }
1057static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1058 const RegionCodeGenTy &ThenGen,
1059 const RegionCodeGenTy &ElseGen) {
1060 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1061
1062 // If the condition constant folds and can be elided, try to avoid emitting
1063 // the condition and the dead arm of the if/else.
1064 bool CondConstant;
1065 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1066 CodeGenFunction::RunCleanupsScope Scope(CGF);
1067 if (CondConstant) {
1068 ThenGen(CGF);
1069 } else {
1070 ElseGen(CGF);
1071 }
1072 return;
1073 }
1074
1075 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1076 // emit the conditional branch.
1077 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1078 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1079 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1080 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1081
1082 // Emit the 'then' code.
1083 CGF.EmitBlock(ThenBlock);
1084 {
1085 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1086 ThenGen(CGF);
1087 }
1088 CGF.EmitBranch(ContBlock);
1089 // Emit the 'else' code if present.
1090 {
1091 // There is no need to emit line number for unconditional branch.
1092 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1093 CGF.EmitBlock(ElseBlock);
1094 }
1095 {
1096 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1097 ElseGen(CGF);
1098 }
1099 {
1100 // There is no need to emit line number for unconditional branch.
1101 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1102 CGF.EmitBranch(ContBlock);
1103 }
1104 // Emit the continuation block for code after the if.
1105 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001106}
1107
Alexey Bataev1d677132015-04-22 13:57:31 +00001108void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1109 llvm::Value *OutlinedFn,
1110 llvm::Value *CapturedStruct,
1111 const Expr *IfCond) {
1112 auto *RTLoc = emitUpdateLocation(CGF, Loc);
1113 auto &&ThenGen =
1114 [this, OutlinedFn, CapturedStruct, RTLoc](CodeGenFunction &CGF) {
1115 // Build call __kmpc_fork_call(loc, 1, microtask,
1116 // captured_struct/*context*/)
1117 llvm::Value *Args[] = {
1118 RTLoc,
1119 CGF.Builder.getInt32(
1120 1), // Number of arguments after 'microtask' argument
1121 // (there is only one additional argument - 'context')
1122 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
1123 CGF.EmitCastToVoidPtr(CapturedStruct)};
1124 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1125 CGF.EmitRuntimeCall(RTLFn, Args);
1126 };
1127 auto &&ElseGen = [this, OutlinedFn, CapturedStruct, RTLoc, Loc](
1128 CodeGenFunction &CGF) {
1129 auto ThreadID = getThreadID(CGF, Loc);
1130 // Build calls:
1131 // __kmpc_serialized_parallel(&Loc, GTid);
1132 llvm::Value *Args[] = {RTLoc, ThreadID};
1133 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1134 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001135
Alexey Bataev1d677132015-04-22 13:57:31 +00001136 // OutlinedFn(&GTid, &zero, CapturedStruct);
1137 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1138 auto Int32Ty = CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32,
1139 /*Signed*/ true);
1140 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
1141 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1142 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
1143 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001144
Alexey Bataev1d677132015-04-22 13:57:31 +00001145 // __kmpc_end_serialized_parallel(&Loc, GTid);
1146 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1147 CGF.EmitRuntimeCall(
1148 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1149 };
1150 if (IfCond) {
1151 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1152 } else {
1153 CodeGenFunction::RunCleanupsScope Scope(CGF);
1154 ThenGen(CGF);
1155 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001156}
1157
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001158// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001159// thread-ID variable (it is passed in a first argument of the outlined function
1160// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1161// regular serial code region, get thread ID by calling kmp_int32
1162// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1163// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001164llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +00001165 SourceLocation Loc) {
1166 if (auto OMPRegionInfo =
1167 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001168 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001169 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001170
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001171 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001172 auto Int32Ty =
1173 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1174 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1175 CGF.EmitStoreOfScalar(ThreadID,
1176 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
1177
1178 return ThreadIDTemp;
1179}
1180
Alexey Bataev97720002014-11-11 04:05:39 +00001181llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001182CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001183 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001184 SmallString<256> Buffer;
1185 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001186 Out << Name;
1187 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001188 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1189 if (Elem.second) {
1190 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001191 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001192 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001193 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001194
David Blaikie13156b62014-11-19 03:06:06 +00001195 return Elem.second = new llvm::GlobalVariable(
1196 CGM.getModule(), Ty, /*IsConstant*/ false,
1197 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1198 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001199}
1200
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001201llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001202 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001203 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001204}
1205
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001206namespace {
Alexey Bataeva744ff52015-05-05 09:24:37 +00001207template <size_t N> class CallEndCleanup : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001208 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001209 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001210
1211public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001212 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1213 : Callee(Callee) {
1214 assert(CleanupArgs.size() == N);
1215 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1216 }
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001217 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1218 CGF.EmitRuntimeCall(Callee, Args);
1219 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001220};
1221} // namespace
1222
1223void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1224 StringRef CriticalName,
1225 const RegionCodeGenTy &CriticalOpGen,
1226 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001227 // __kmpc_critical(ident_t *, gtid, Lock);
1228 // CriticalOpGen();
1229 // __kmpc_end_critical(ident_t *, gtid, Lock);
1230 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001231 {
1232 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001233 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1234 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001235 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001236 // Build a call to __kmpc_end_critical
Alexey Bataeva744ff52015-05-05 09:24:37 +00001237 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001238 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1239 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001240 emitInlinedDirective(CGF, CriticalOpGen);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001241 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001242}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001243
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001244static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001245 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001246 llvm::Value *CallBool = CGF.EmitScalarConversion(
1247 IfCond,
1248 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
1249 CGF.getContext().BoolTy);
1250
1251 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1252 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1253 // Generate the branch (If-stmt)
1254 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1255 CGF.EmitBlock(ThenBlock);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001256 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001257 // Emit the rest of bblocks/branches
1258 CGF.EmitBranch(ContBlock);
1259 CGF.EmitBlock(ContBlock, true);
1260}
1261
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001262void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001263 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001264 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001265 // if(__kmpc_master(ident_t *, gtid)) {
1266 // MasterOpGen();
1267 // __kmpc_end_master(ident_t *, gtid);
1268 // }
1269 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001270 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001271 auto *IsMaster =
1272 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001273 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1274 MasterCallEndCleanup;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001275 emitIfStmt(CGF, IsMaster, [&](CodeGenFunction &CGF) -> void {
1276 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001277 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001278 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1279 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001280 MasterOpGen(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00001281 });
1282}
1283
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001284void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1285 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001286 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1287 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001288 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001289 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001290 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001291}
1292
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001293void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1294 const RegionCodeGenTy &TaskgroupOpGen,
1295 SourceLocation Loc) {
1296 // __kmpc_taskgroup(ident_t *, gtid);
1297 // TaskgroupOpGen();
1298 // __kmpc_end_taskgroup(ident_t *, gtid);
1299 // Prepare arguments and build a call to __kmpc_taskgroup
1300 {
1301 CodeGenFunction::RunCleanupsScope Scope(CGF);
1302 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1303 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1304 // Build a call to __kmpc_end_taskgroup
1305 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1306 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1307 llvm::makeArrayRef(Args));
1308 emitInlinedDirective(CGF, TaskgroupOpGen);
1309 }
1310}
1311
Alexey Bataeva63048e2015-03-23 06:18:07 +00001312static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001313 CodeGenModule &CGM, llvm::Type *ArgsType,
1314 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1315 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001316 auto &C = CGM.getContext();
1317 // void copy_func(void *LHSArg, void *RHSArg);
1318 FunctionArgList Args;
1319 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1320 C.VoidPtrTy);
1321 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1322 C.VoidPtrTy);
1323 Args.push_back(&LHSArg);
1324 Args.push_back(&RHSArg);
1325 FunctionType::ExtInfo EI;
1326 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1327 C.VoidTy, Args, EI, /*isVariadic=*/false);
1328 auto *Fn = llvm::Function::Create(
1329 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1330 ".omp.copyprivate.copy_func", &CGM.getModule());
1331 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1332 CodeGenFunction CGF(CGM);
1333 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001334 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001335 // Src = (void*[n])(RHSArg);
1336 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1337 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1338 CGF.PointerAlignInBytes),
1339 ArgsType);
1340 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1341 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1342 CGF.PointerAlignInBytes),
1343 ArgsType);
1344 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1345 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1346 // ...
1347 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001348 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataev420d45b2015-04-14 05:11:24 +00001349 auto *DestAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1350 CGF.Builder.CreateAlignedLoad(
1351 CGF.Builder.CreateStructGEP(nullptr, LHS, I),
1352 CGM.PointerAlignInBytes),
1353 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1354 auto *SrcAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1355 CGF.Builder.CreateAlignedLoad(
1356 CGF.Builder.CreateStructGEP(nullptr, RHS, I),
1357 CGM.PointerAlignInBytes),
1358 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001359 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1360 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001361 CGF.EmitOMPCopy(CGF, Type, DestAddr, SrcAddr,
Alexey Bataev420d45b2015-04-14 05:11:24 +00001362 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()),
1363 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
1364 AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001365 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001366 CGF.FinishFunction();
1367 return Fn;
1368}
1369
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001370void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001371 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001372 SourceLocation Loc,
1373 ArrayRef<const Expr *> CopyprivateVars,
1374 ArrayRef<const Expr *> SrcExprs,
1375 ArrayRef<const Expr *> DstExprs,
1376 ArrayRef<const Expr *> AssignmentOps) {
1377 assert(CopyprivateVars.size() == SrcExprs.size() &&
1378 CopyprivateVars.size() == DstExprs.size() &&
1379 CopyprivateVars.size() == AssignmentOps.size());
1380 auto &C = CGM.getContext();
1381 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001382 // if(__kmpc_single(ident_t *, gtid)) {
1383 // SingleOpGen();
1384 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001385 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001386 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001387 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1388 // <copy_func>, did_it);
1389
1390 llvm::AllocaInst *DidIt = nullptr;
1391 if (!CopyprivateVars.empty()) {
1392 // int32 did_it = 0;
1393 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1394 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
Alexey Bataev66beaa92015-04-30 03:47:32 +00001395 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(0), DidIt,
1396 DidIt->getAlignment());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001397 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001398 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001399 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001400 auto *IsSingle =
1401 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001402 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1403 SingleCallEndCleanup;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001404 emitIfStmt(CGF, IsSingle, [&](CodeGenFunction &CGF) -> void {
1405 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001406 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001407 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1408 llvm::makeArrayRef(Args));
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001409 SingleOpGen(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001410 if (DidIt) {
1411 // did_it = 1;
1412 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1413 DidIt->getAlignment());
1414 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001415 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001416 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1417 // <copy_func>, did_it);
1418 if (DidIt) {
1419 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1420 auto CopyprivateArrayTy =
1421 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1422 /*IndexTypeQuals=*/0);
1423 // Create a list of all private variables for copyprivate.
1424 auto *CopyprivateList =
1425 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1426 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001427 auto *Elem = CGF.Builder.CreateStructGEP(
1428 CopyprivateList->getAllocatedType(), CopyprivateList, I);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001429 CGF.Builder.CreateAlignedStore(
1430 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1431 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1432 Elem, CGM.PointerAlignInBytes);
1433 }
1434 // Build function that copies private values from single region to all other
1435 // threads in the corresponding parallel region.
1436 auto *CpyFn = emitCopyprivateCopyFunction(
1437 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001438 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001439 auto *BufSize = llvm::ConstantInt::get(
1440 CGM.SizeTy, C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001441 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1442 CGF.VoidPtrTy);
1443 auto *DidItVal =
1444 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1445 llvm::Value *Args[] = {
1446 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1447 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001448 BufSize, // size_t <buf_size>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001449 CL, // void *<copyprivate list>
1450 CpyFn, // void (*) (void *, void *) <copy_func>
1451 DidItVal // i32 did_it
1452 };
1453 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1454 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001455}
1456
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001457void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1458 const RegionCodeGenTy &OrderedOpGen,
1459 SourceLocation Loc) {
1460 // __kmpc_ordered(ident_t *, gtid);
1461 // OrderedOpGen();
1462 // __kmpc_end_ordered(ident_t *, gtid);
1463 // Prepare arguments and build a call to __kmpc_ordered
1464 {
1465 CodeGenFunction::RunCleanupsScope Scope(CGF);
1466 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1467 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1468 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001469 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001470 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1471 llvm::makeArrayRef(Args));
1472 emitInlinedDirective(CGF, OrderedOpGen);
1473 }
1474}
1475
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001476void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf2685682015-03-30 04:30:22 +00001477 OpenMPDirectiveKind Kind) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001478 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001479 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1480 if (Kind == OMPD_for) {
1481 Flags =
1482 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1483 } else if (Kind == OMPD_sections) {
1484 Flags = static_cast<OpenMPLocationFlags>(Flags |
1485 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1486 } else if (Kind == OMPD_single) {
1487 Flags =
1488 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1489 } else if (Kind == OMPD_barrier) {
1490 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1491 } else {
1492 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1493 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001494 // Build call __kmpc_cancel_barrier(loc, thread_id);
1495 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1496 // one provides the same functionality and adds initial support for
1497 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1498 // is provided default by the runtime library so it safe to make such
1499 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001500 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1501 getThreadID(CGF, Loc)};
1502 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001503}
1504
Alexander Musmanc6388682014-12-15 07:07:06 +00001505/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1506/// the enum sched_type in kmp.h).
1507enum OpenMPSchedType {
1508 /// \brief Lower bound for default (unordered) versions.
1509 OMP_sch_lower = 32,
1510 OMP_sch_static_chunked = 33,
1511 OMP_sch_static = 34,
1512 OMP_sch_dynamic_chunked = 35,
1513 OMP_sch_guided_chunked = 36,
1514 OMP_sch_runtime = 37,
1515 OMP_sch_auto = 38,
1516 /// \brief Lower bound for 'ordered' versions.
1517 OMP_ord_lower = 64,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001518 OMP_ord_static_chunked = 65,
1519 OMP_ord_static = 66,
1520 OMP_ord_dynamic_chunked = 67,
1521 OMP_ord_guided_chunked = 68,
1522 OMP_ord_runtime = 69,
1523 OMP_ord_auto = 70,
1524 OMP_sch_default = OMP_sch_static,
Alexander Musmanc6388682014-12-15 07:07:06 +00001525};
1526
1527/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1528static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001529 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001530 switch (ScheduleKind) {
1531 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001532 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
1533 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00001534 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001535 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001536 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001537 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001538 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001539 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
1540 case OMPC_SCHEDULE_auto:
1541 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00001542 case OMPC_SCHEDULE_unknown:
1543 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001544 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00001545 }
1546 llvm_unreachable("Unexpected runtime schedule");
1547}
1548
1549bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1550 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001551 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00001552 return Schedule == OMP_sch_static;
1553}
1554
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001555bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001556 auto Schedule =
1557 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001558 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1559 return Schedule != OMP_sch_static;
1560}
1561
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001562void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1563 OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001564 unsigned IVSize, bool IVSigned, bool Ordered,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001565 llvm::Value *IL, llvm::Value *LB,
1566 llvm::Value *UB, llvm::Value *ST,
1567 llvm::Value *Chunk) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001568 OpenMPSchedType Schedule =
1569 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
1570 if (Ordered ||
1571 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
1572 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked)) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001573 // Call __kmpc_dispatch_init(
1574 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1575 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1576 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001577
Alexander Musman92bdaab2015-03-12 13:37:50 +00001578 // If the Chunk was not specified in the clause - use default value 1.
1579 if (Chunk == nullptr)
1580 Chunk = CGF.Builder.getIntN(IVSize, 1);
1581 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1582 getThreadID(CGF, Loc),
1583 CGF.Builder.getInt32(Schedule), // Schedule type
1584 CGF.Builder.getIntN(IVSize, 0), // Lower
1585 UB, // Upper
1586 CGF.Builder.getIntN(IVSize, 1), // Stride
1587 Chunk // Chunk
1588 };
1589 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1590 } else {
1591 // Call __kmpc_for_static_init(
1592 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1593 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1594 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1595 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1596 if (Chunk == nullptr) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001597 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
Alexander Musman92bdaab2015-03-12 13:37:50 +00001598 "expected static non-chunked schedule");
1599 // If the Chunk was not specified in the clause - use default value 1.
1600 Chunk = CGF.Builder.getIntN(IVSize, 1);
1601 } else
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001602 assert((Schedule == OMP_sch_static_chunked ||
1603 Schedule == OMP_ord_static_chunked) &&
Alexander Musman92bdaab2015-03-12 13:37:50 +00001604 "expected static chunked schedule");
1605 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1606 getThreadID(CGF, Loc),
1607 CGF.Builder.getInt32(Schedule), // Schedule type
1608 IL, // &isLastIter
1609 LB, // &LB
1610 UB, // &UB
1611 ST, // &Stride
1612 CGF.Builder.getIntN(IVSize, 1), // Incr
1613 Chunk // Chunk
1614 };
Alexander Musman21212e42015-03-13 10:38:23 +00001615 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001616 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001617}
1618
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001619void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
1620 SourceLocation Loc) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001621 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001622 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1623 getThreadID(CGF, Loc)};
1624 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1625 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001626}
1627
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001628void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
1629 SourceLocation Loc,
1630 unsigned IVSize,
1631 bool IVSigned) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001632 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
1633 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1634 getThreadID(CGF, Loc)};
1635 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
1636}
1637
Alexander Musman92bdaab2015-03-12 13:37:50 +00001638llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1639 SourceLocation Loc, unsigned IVSize,
1640 bool IVSigned, llvm::Value *IL,
1641 llvm::Value *LB, llvm::Value *UB,
1642 llvm::Value *ST) {
1643 // Call __kmpc_dispatch_next(
1644 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1645 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1646 // kmp_int[32|64] *p_stride);
1647 llvm::Value *Args[] = {
1648 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1649 IL, // &isLastIter
1650 LB, // &Lower
1651 UB, // &Upper
1652 ST // &Stride
1653 };
1654 llvm::Value *Call =
1655 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1656 return CGF.EmitScalarConversion(
1657 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1658 CGF.getContext().BoolTy);
1659}
1660
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001661void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1662 llvm::Value *NumThreads,
1663 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001664 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1665 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001666 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001667 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001668 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1669 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001670}
1671
Alexey Bataev7f210c62015-06-18 13:40:03 +00001672void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
1673 OpenMPProcBindClauseKind ProcBind,
1674 SourceLocation Loc) {
1675 // Constants for proc bind value accepted by the runtime.
1676 enum ProcBindTy {
1677 ProcBindFalse = 0,
1678 ProcBindTrue,
1679 ProcBindMaster,
1680 ProcBindClose,
1681 ProcBindSpread,
1682 ProcBindIntel,
1683 ProcBindDefault
1684 } RuntimeProcBind;
1685 switch (ProcBind) {
1686 case OMPC_PROC_BIND_master:
1687 RuntimeProcBind = ProcBindMaster;
1688 break;
1689 case OMPC_PROC_BIND_close:
1690 RuntimeProcBind = ProcBindClose;
1691 break;
1692 case OMPC_PROC_BIND_spread:
1693 RuntimeProcBind = ProcBindSpread;
1694 break;
1695 case OMPC_PROC_BIND_unknown:
1696 llvm_unreachable("Unsupported proc_bind value.");
1697 }
1698 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
1699 llvm::Value *Args[] = {
1700 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1701 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
1702 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
1703}
1704
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001705void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1706 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001707 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001708 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1709 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001710}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001711
Alexey Bataev62b63b12015-03-10 07:28:44 +00001712namespace {
1713/// \brief Indexes of fields for type kmp_task_t.
1714enum KmpTaskTFields {
1715 /// \brief List of shared variables.
1716 KmpTaskTShareds,
1717 /// \brief Task routine.
1718 KmpTaskTRoutine,
1719 /// \brief Partition id for the untied tasks.
1720 KmpTaskTPartId,
1721 /// \brief Function with call of destructors for private variables.
1722 KmpTaskTDestructors,
1723};
1724} // namespace
1725
1726void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1727 if (!KmpRoutineEntryPtrTy) {
1728 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1729 auto &C = CGM.getContext();
1730 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1731 FunctionProtoType::ExtProtoInfo EPI;
1732 KmpRoutineEntryPtrQTy = C.getPointerType(
1733 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1734 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1735 }
1736}
1737
1738static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1739 QualType FieldTy) {
1740 auto *Field = FieldDecl::Create(
1741 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1742 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1743 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1744 Field->setAccess(AS_public);
1745 DC->addDecl(Field);
1746}
1747
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001748namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00001749struct PrivateHelpersTy {
1750 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
1751 const VarDecl *PrivateElemInit)
1752 : Original(Original), PrivateCopy(PrivateCopy),
1753 PrivateElemInit(PrivateElemInit) {}
1754 const VarDecl *Original;
1755 const VarDecl *PrivateCopy;
1756 const VarDecl *PrivateElemInit;
1757};
1758typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001759} // namespace
1760
Alexey Bataev9e034042015-05-05 04:05:12 +00001761static RecordDecl *
1762createPrivatesRecordDecl(CodeGenModule &CGM,
1763 const ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001764 if (!Privates.empty()) {
1765 auto &C = CGM.getContext();
1766 // Build struct .kmp_privates_t. {
1767 // /* private vars */
1768 // };
1769 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
1770 RD->startDefinition();
1771 for (auto &&Pair : Privates) {
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001772 auto Type = Pair.second.Original->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001773 Type = Type.getNonReferenceType();
1774 addFieldToRecordDecl(C, RD, Type);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001775 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001776 RD->completeDefinition();
1777 return RD;
1778 }
1779 return nullptr;
1780}
1781
Alexey Bataev9e034042015-05-05 04:05:12 +00001782static RecordDecl *
1783createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001784 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001785 auto &C = CGM.getContext();
1786 // Build struct kmp_task_t {
1787 // void * shareds;
1788 // kmp_routine_entry_t routine;
1789 // kmp_int32 part_id;
1790 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001791 // };
1792 auto *RD = C.buildImplicitRecord("kmp_task_t");
1793 RD->startDefinition();
1794 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1795 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1796 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1797 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001798 RD->completeDefinition();
1799 return RD;
1800}
1801
1802static RecordDecl *
1803createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
1804 const ArrayRef<PrivateDataTy> Privates) {
1805 auto &C = CGM.getContext();
1806 // Build struct kmp_task_t_with_privates {
1807 // kmp_task_t task_data;
1808 // .kmp_privates_t. privates;
1809 // };
1810 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
1811 RD->startDefinition();
1812 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001813 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
1814 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
1815 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001816 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001817 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001818}
1819
1820/// \brief Emit a proxy function which accepts kmp_task_t as the second
1821/// argument.
1822/// \code
1823/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001824/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
1825/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001826/// return 0;
1827/// }
1828/// \endcode
1829static llvm::Value *
1830emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001831 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
1832 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001833 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1834 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001835 auto &C = CGM.getContext();
1836 FunctionArgList Args;
1837 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1838 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001839 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001840 Args.push_back(&GtidArg);
1841 Args.push_back(&TaskTypeArg);
1842 FunctionType::ExtInfo Info;
1843 auto &TaskEntryFnInfo =
1844 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1845 /*isVariadic=*/false);
1846 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1847 auto *TaskEntry =
1848 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1849 ".omp_task_entry.", &CGM.getModule());
1850 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1851 CodeGenFunction CGF(CGM);
1852 CGF.disableDebugInfo();
1853 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1854
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001855 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
1856 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001857 auto *GtidParam = CGF.EmitLoadOfScalar(
1858 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1859 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001860 auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
1861 CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001862 LValue TDBase =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001863 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
1864 auto *KmpTaskTWithPrivatesQTyRD =
1865 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001866 LValue Base =
1867 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001868 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
1869 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
1870 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
1871 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
1872
1873 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
1874 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001875 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001876 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001877 CGF.ConvertTypeForMem(SharedsPtrTy));
1878
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001879 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
1880 llvm::Value *PrivatesParam;
1881 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
1882 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
1883 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1884 PrivatesLVal.getAddress(), CGF.VoidPtrTy);
1885 } else {
1886 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
1887 }
1888
1889 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
1890 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00001891 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1892 CGF.EmitStoreThroughLValue(
1893 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1894 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1895 CGF.FinishFunction();
1896 return TaskEntry;
1897}
1898
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001899static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
1900 SourceLocation Loc,
1901 QualType KmpInt32Ty,
1902 QualType KmpTaskTWithPrivatesPtrQTy,
1903 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001904 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001905 FunctionArgList Args;
1906 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1907 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001908 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001909 Args.push_back(&GtidArg);
1910 Args.push_back(&TaskTypeArg);
1911 FunctionType::ExtInfo Info;
1912 auto &DestructorFnInfo =
1913 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1914 /*isVariadic=*/false);
1915 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
1916 auto *DestructorFn =
1917 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
1918 ".omp_task_destructor.", &CGM.getModule());
1919 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, DestructorFnInfo, DestructorFn);
1920 CodeGenFunction CGF(CGM);
1921 CGF.disableDebugInfo();
1922 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
1923 Args);
1924
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001925 auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
1926 CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
1927 LValue Base =
1928 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
1929 auto *KmpTaskTWithPrivatesQTyRD =
1930 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
1931 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001932 Base = CGF.EmitLValueForField(Base, *FI);
1933 for (auto *Field :
1934 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
1935 if (auto DtorKind = Field->getType().isDestructedType()) {
1936 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
1937 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
1938 }
1939 }
1940 CGF.FinishFunction();
1941 return DestructorFn;
1942}
1943
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001944/// \brief Emit a privates mapping function for correct handling of private and
1945/// firstprivate variables.
1946/// \code
1947/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
1948/// **noalias priv1,..., <tyn> **noalias privn) {
1949/// *priv1 = &.privates.priv1;
1950/// ...;
1951/// *privn = &.privates.privn;
1952/// }
1953/// \endcode
1954static llvm::Value *
1955emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
1956 const ArrayRef<const Expr *> PrivateVars,
1957 const ArrayRef<const Expr *> FirstprivateVars,
1958 QualType PrivatesQTy,
1959 const ArrayRef<PrivateDataTy> Privates) {
1960 auto &C = CGM.getContext();
1961 FunctionArgList Args;
1962 ImplicitParamDecl TaskPrivatesArg(
1963 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1964 C.getPointerType(PrivatesQTy).withConst().withRestrict());
1965 Args.push_back(&TaskPrivatesArg);
1966 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
1967 unsigned Counter = 1;
1968 for (auto *E: PrivateVars) {
1969 Args.push_back(ImplicitParamDecl::Create(
1970 C, /*DC=*/nullptr, Loc,
1971 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
1972 .withConst()
1973 .withRestrict()));
1974 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1975 PrivateVarsPos[VD] = Counter;
1976 ++Counter;
1977 }
1978 for (auto *E : FirstprivateVars) {
1979 Args.push_back(ImplicitParamDecl::Create(
1980 C, /*DC=*/nullptr, Loc,
1981 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
1982 .withConst()
1983 .withRestrict()));
1984 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1985 PrivateVarsPos[VD] = Counter;
1986 ++Counter;
1987 }
1988 FunctionType::ExtInfo Info;
1989 auto &TaskPrivatesMapFnInfo =
1990 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
1991 /*isVariadic=*/false);
1992 auto *TaskPrivatesMapTy =
1993 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
1994 auto *TaskPrivatesMap = llvm::Function::Create(
1995 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
1996 ".omp_task_privates_map.", &CGM.getModule());
1997 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskPrivatesMapFnInfo,
1998 TaskPrivatesMap);
1999 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
2000 CodeGenFunction CGF(CGM);
2001 CGF.disableDebugInfo();
2002 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
2003 TaskPrivatesMapFnInfo, Args);
2004
2005 // *privi = &.privates.privi;
2006 auto *TaskPrivatesArgAddr = CGF.Builder.CreateAlignedLoad(
2007 CGF.GetAddrOfLocalVar(&TaskPrivatesArg), CGM.PointerAlignInBytes);
2008 LValue Base =
2009 CGF.MakeNaturalAlignAddrLValue(TaskPrivatesArgAddr, PrivatesQTy);
2010 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
2011 Counter = 0;
2012 for (auto *Field : PrivatesQTyRD->fields()) {
2013 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
2014 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
2015 auto RefLVal = CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(VD),
2016 VD->getType());
2017 auto RefLoadRVal = CGF.EmitLoadOfLValue(RefLVal, Loc);
2018 CGF.EmitStoreOfScalar(
2019 FieldLVal.getAddress(),
2020 CGF.MakeNaturalAlignAddrLValue(RefLoadRVal.getScalarVal(),
2021 RefLVal.getType()->getPointeeType()));
2022 ++Counter;
2023 }
2024 CGF.FinishFunction();
2025 return TaskPrivatesMap;
2026}
2027
Alexey Bataev9e034042015-05-05 04:05:12 +00002028static int array_pod_sort_comparator(const PrivateDataTy *P1,
2029 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002030 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
2031}
2032
2033void CGOpenMPRuntime::emitTaskCall(
2034 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
2035 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
2036 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002037 const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
2038 ArrayRef<const Expr *> PrivateCopies,
2039 ArrayRef<const Expr *> FirstprivateVars,
2040 ArrayRef<const Expr *> FirstprivateCopies,
2041 ArrayRef<const Expr *> FirstprivateInits,
2042 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002043 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00002044 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002045 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00002046 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002047 for (auto *E : PrivateVars) {
2048 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2049 Privates.push_back(std::make_pair(
2050 C.getTypeAlignInChars(VD->getType()),
Alexey Bataev9e034042015-05-05 04:05:12 +00002051 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2052 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002053 ++I;
2054 }
Alexey Bataev9e034042015-05-05 04:05:12 +00002055 I = FirstprivateCopies.begin();
2056 auto IElemInitRef = FirstprivateInits.begin();
2057 for (auto *E : FirstprivateVars) {
2058 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2059 Privates.push_back(std::make_pair(
2060 C.getTypeAlignInChars(VD->getType()),
2061 PrivateHelpersTy(
2062 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
2063 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
2064 ++I, ++IElemInitRef;
2065 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002066 llvm::array_pod_sort(Privates.begin(), Privates.end(),
2067 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002068 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2069 // Build type kmp_routine_entry_t (if not built yet).
2070 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002071 // Build type kmp_task_t (if not built yet).
2072 if (KmpTaskTQTy.isNull()) {
2073 KmpTaskTQTy = C.getRecordType(
2074 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
2075 }
2076 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002077 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002078 auto *KmpTaskTWithPrivatesQTyRD =
2079 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
2080 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
2081 QualType KmpTaskTWithPrivatesPtrQTy =
2082 C.getPointerType(KmpTaskTWithPrivatesQTy);
2083 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
2084 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
2085 auto KmpTaskTWithPrivatesTySize =
2086 CGM.getSize(C.getTypeSizeInChars(KmpTaskTWithPrivatesQTy));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002087 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
2088
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002089 // Emit initial values for private copies (if any).
2090 llvm::Value *TaskPrivatesMap = nullptr;
2091 auto *TaskPrivatesMapTy =
2092 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
2093 3)
2094 ->getType();
2095 if (!Privates.empty()) {
2096 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2097 TaskPrivatesMap = emitTaskPrivateMappingFunction(
2098 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
2099 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2100 TaskPrivatesMap, TaskPrivatesMapTy);
2101 } else {
2102 TaskPrivatesMap = llvm::ConstantPointerNull::get(
2103 cast<llvm::PointerType>(TaskPrivatesMapTy));
2104 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002105 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
2106 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002107 auto *TaskEntry = emitProxyTaskFunction(
2108 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002109 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002110
2111 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
2112 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2113 // kmp_routine_entry_t *task_entry);
2114 // Task flags. Format is taken from
2115 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
2116 // description of kmp_tasking_flags struct.
2117 const unsigned TiedFlag = 0x1;
2118 const unsigned FinalFlag = 0x2;
2119 unsigned Flags = Tied ? TiedFlag : 0;
2120 auto *TaskFlags =
2121 Final.getPointer()
2122 ? CGF.Builder.CreateSelect(Final.getPointer(),
2123 CGF.Builder.getInt32(FinalFlag),
2124 CGF.Builder.getInt32(/*C=*/0))
2125 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
2126 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
2127 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002128 llvm::Value *AllocArgs[] = {
2129 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), TaskFlags,
2130 KmpTaskTWithPrivatesTySize, CGM.getSize(SharedsSize),
2131 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskEntry,
2132 KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002133 auto *NewTask = CGF.EmitRuntimeCall(
2134 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002135 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2136 NewTask, KmpTaskTWithPrivatesPtrTy);
2137 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
2138 KmpTaskTWithPrivatesQTy);
2139 LValue TDBase =
2140 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002141 // Fill the data in the resulting kmp_task_t record.
2142 // Copy shareds if there are any.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002143 llvm::Value *KmpTaskSharedsPtr = nullptr;
2144 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
2145 KmpTaskSharedsPtr = CGF.EmitLoadOfScalar(
2146 CGF.EmitLValueForField(
2147 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)),
2148 Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002149 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002150 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002151 // Emit initial values for private copies (if any).
2152 bool NeedsCleanup = false;
2153 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002154 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2155 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002156 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002157 LValue SharedsBase;
2158 if (!FirstprivateVars.empty()) {
2159 SharedsBase = CGF.MakeNaturalAlignAddrLValue(
2160 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2161 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
2162 SharedsTy);
2163 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002164 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
2165 cast<CapturedStmt>(*D.getAssociatedStmt()));
2166 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002167 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002168 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002169 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002170 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002171 if (auto *Elem = Pair.second.PrivateElemInit) {
2172 auto *OriginalVD = Pair.second.Original;
2173 auto *SharedField = CapturesInfo.lookup(OriginalVD);
2174 auto SharedRefLValue =
2175 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002176 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002177 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002178 // Initialize firstprivate array.
2179 if (!isa<CXXConstructExpr>(Init) ||
2180 CGF.isTrivialInitializer(Init)) {
2181 // Perform simple memcpy.
2182 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002183 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00002184 } else {
2185 // Initialize firstprivate array using element-by-element
2186 // intialization.
2187 CGF.EmitOMPAggregateAssign(
2188 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002189 Type, [&CGF, Elem, Init, &CapturesInfo](
2190 llvm::Value *DestElement, llvm::Value *SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002191 // Clean up any temporaries needed by the initialization.
2192 CodeGenFunction::OMPPrivateScope InitScope(CGF);
2193 InitScope.addPrivate(Elem, [SrcElement]() -> llvm::Value *{
2194 return SrcElement;
2195 });
2196 (void)InitScope.Privatize();
2197 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00002198 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
2199 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002200 CGF.EmitAnyExprToMem(Init, DestElement,
2201 Init->getType().getQualifiers(),
2202 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002203 });
2204 }
2205 } else {
2206 CodeGenFunction::OMPPrivateScope InitScope(CGF);
2207 InitScope.addPrivate(Elem, [SharedRefLValue]() -> llvm::Value *{
2208 return SharedRefLValue.getAddress();
2209 });
2210 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00002211 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00002212 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
2213 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00002214 }
2215 } else {
2216 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
2217 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002218 }
2219 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002220 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002221 }
2222 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002223 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002224 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002225 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
2226 KmpTaskTWithPrivatesPtrQTy,
2227 KmpTaskTWithPrivatesQTy)
2228 : llvm::ConstantPointerNull::get(
2229 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
2230 LValue Destructor = CGF.EmitLValueForField(
2231 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
2232 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2233 DestructorFn, KmpRoutineEntryPtrTy),
2234 Destructor);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002235
2236 // Process list of dependences.
2237 llvm::Value *DependInfo = nullptr;
2238 unsigned DependencesNumber = Dependences.size();
2239 if (!Dependences.empty()) {
2240 // Dependence kind for RTL.
2241 enum RTLDependenceKindTy { DepIn = 1, DepOut = 2, DepInOut = 3 };
2242 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
2243 RecordDecl *KmpDependInfoRD;
2244 QualType FlagsTy = C.getIntTypeForBitwidth(
2245 C.toBits(C.getTypeSizeInChars(C.BoolTy)), /*Signed=*/false);
2246 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
2247 if (KmpDependInfoTy.isNull()) {
2248 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
2249 KmpDependInfoRD->startDefinition();
2250 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
2251 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
2252 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
2253 KmpDependInfoRD->completeDefinition();
2254 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
2255 } else {
2256 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
2257 }
2258 // Define type kmp_depend_info[<Dependences.size()>];
2259 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
2260 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, Dependences.size()),
2261 ArrayType::Normal, /*IndexTypeQuals=*/0);
2262 // kmp_depend_info[<Dependences.size()>] deps;
2263 DependInfo = CGF.CreateMemTemp(KmpDependInfoArrayTy);
2264 for (unsigned i = 0; i < DependencesNumber; ++i) {
2265 auto Addr = CGF.EmitLValue(Dependences[i].second);
2266 auto *Size = llvm::ConstantInt::get(
2267 CGF.SizeTy,
2268 C.getTypeSizeInChars(Dependences[i].second->getType()).getQuantity());
2269 auto Base = CGF.MakeNaturalAlignAddrLValue(
2270 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, DependInfo, i),
2271 KmpDependInfoTy);
2272 // deps[i].base_addr = &<Dependences[i].second>;
2273 auto BaseAddrLVal = CGF.EmitLValueForField(
2274 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
2275 CGF.EmitStoreOfScalar(
2276 CGF.Builder.CreatePtrToInt(Addr.getAddress(), CGF.IntPtrTy),
2277 BaseAddrLVal);
2278 // deps[i].len = sizeof(<Dependences[i].second>);
2279 auto LenLVal = CGF.EmitLValueForField(
2280 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
2281 CGF.EmitStoreOfScalar(Size, LenLVal);
2282 // deps[i].flags = <Dependences[i].first>;
2283 RTLDependenceKindTy DepKind;
2284 switch (Dependences[i].first) {
2285 case OMPC_DEPEND_in:
2286 DepKind = DepIn;
2287 break;
2288 case OMPC_DEPEND_out:
2289 DepKind = DepOut;
2290 break;
2291 case OMPC_DEPEND_inout:
2292 DepKind = DepInOut;
2293 break;
2294 case OMPC_DEPEND_unknown:
2295 llvm_unreachable("Unknown task dependence type");
2296 }
2297 auto FlagsLVal = CGF.EmitLValueForField(
2298 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
2299 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
2300 FlagsLVal);
2301 }
2302 DependInfo = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2303 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, DependInfo, 0),
2304 CGF.VoidPtrTy);
2305 }
2306
Alexey Bataev62b63b12015-03-10 07:28:44 +00002307 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
2308 // libcall.
2309 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
2310 // *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002311 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2312 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2313 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
2314 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00002315 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002316 auto *UpLoc = emitUpdateLocation(CGF, Loc);
2317 llvm::Value *TaskArgs[] = {UpLoc, ThreadID, NewTask};
2318 llvm::Value *DepTaskArgs[] = {
2319 UpLoc,
2320 ThreadID,
2321 NewTask,
2322 DependInfo ? CGF.Builder.getInt32(DependencesNumber) : nullptr,
2323 DependInfo,
2324 DependInfo ? CGF.Builder.getInt32(0) : nullptr,
2325 DependInfo ? llvm::ConstantPointerNull::get(CGF.VoidPtrTy) : nullptr};
2326 auto &&ThenCodeGen = [this, DependInfo, &TaskArgs,
2327 &DepTaskArgs](CodeGenFunction &CGF) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002328 // TODO: add check for untied tasks.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002329 CGF.EmitRuntimeCall(
2330 createRuntimeFunction(DependInfo ? OMPRTL__kmpc_omp_task_with_deps
2331 : OMPRTL__kmpc_omp_task),
2332 DependInfo ? makeArrayRef(DepTaskArgs) : makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00002333 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002334 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
2335 IfCallEndCleanup;
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002336 llvm::Value *DepWaitTaskArgs[] = {
2337 UpLoc,
2338 ThreadID,
2339 DependInfo ? CGF.Builder.getInt32(DependencesNumber) : nullptr,
2340 DependInfo,
2341 DependInfo ? CGF.Builder.getInt32(0) : nullptr,
2342 DependInfo ? llvm::ConstantPointerNull::get(CGF.VoidPtrTy) : nullptr};
2343 auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
2344 DependInfo, &DepWaitTaskArgs](CodeGenFunction &CGF) {
2345 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
2346 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2347 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
2348 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
2349 // is specified.
2350 if (DependInfo)
2351 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
2352 DepWaitTaskArgs);
2353 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
2354 // kmp_task_t *new_task);
2355 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
2356 TaskArgs);
2357 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
2358 // kmp_task_t *new_task);
2359 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
2360 NormalAndEHCleanup,
2361 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
2362 llvm::makeArrayRef(TaskArgs));
Alexey Bataev1d677132015-04-22 13:57:31 +00002363
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002364 // Call proxy_task_entry(gtid, new_task);
2365 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
2366 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
2367 };
Alexey Bataev1d677132015-04-22 13:57:31 +00002368 if (IfCond) {
2369 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
2370 } else {
2371 CodeGenFunction::RunCleanupsScope Scope(CGF);
2372 ThenCodeGen(CGF);
2373 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002374}
2375
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002376static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
2377 llvm::Type *ArgsType,
2378 ArrayRef<const Expr *> LHSExprs,
2379 ArrayRef<const Expr *> RHSExprs,
2380 ArrayRef<const Expr *> ReductionOps) {
2381 auto &C = CGM.getContext();
2382
2383 // void reduction_func(void *LHSArg, void *RHSArg);
2384 FunctionArgList Args;
2385 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2386 C.VoidPtrTy);
2387 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2388 C.VoidPtrTy);
2389 Args.push_back(&LHSArg);
2390 Args.push_back(&RHSArg);
2391 FunctionType::ExtInfo EI;
2392 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2393 C.VoidTy, Args, EI, /*isVariadic=*/false);
2394 auto *Fn = llvm::Function::Create(
2395 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2396 ".omp.reduction.reduction_func", &CGM.getModule());
2397 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
2398 CodeGenFunction CGF(CGM);
2399 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2400
2401 // Dst = (void*[n])(LHSArg);
2402 // Src = (void*[n])(RHSArg);
2403 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2404 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
2405 CGF.PointerAlignInBytes),
2406 ArgsType);
2407 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2408 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
2409 CGF.PointerAlignInBytes),
2410 ArgsType);
2411
2412 // ...
2413 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
2414 // ...
2415 CodeGenFunction::OMPPrivateScope Scope(CGF);
2416 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
2417 Scope.addPrivate(
2418 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()),
2419 [&]() -> llvm::Value *{
2420 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2421 CGF.Builder.CreateAlignedLoad(
2422 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, RHS, I),
2423 CGM.PointerAlignInBytes),
2424 CGF.ConvertTypeForMem(C.getPointerType(RHSExprs[I]->getType())));
2425 });
2426 Scope.addPrivate(
2427 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()),
2428 [&]() -> llvm::Value *{
2429 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2430 CGF.Builder.CreateAlignedLoad(
2431 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, LHS, I),
2432 CGM.PointerAlignInBytes),
2433 CGF.ConvertTypeForMem(C.getPointerType(LHSExprs[I]->getType())));
2434 });
2435 }
2436 Scope.Privatize();
2437 for (auto *E : ReductionOps) {
2438 CGF.EmitIgnoredExpr(E);
2439 }
2440 Scope.ForceCleanup();
2441 CGF.FinishFunction();
2442 return Fn;
2443}
2444
2445void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
2446 ArrayRef<const Expr *> LHSExprs,
2447 ArrayRef<const Expr *> RHSExprs,
2448 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002449 bool WithNowait, bool SimpleReduction) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002450 // Next code should be emitted for reduction:
2451 //
2452 // static kmp_critical_name lock = { 0 };
2453 //
2454 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
2455 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
2456 // ...
2457 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
2458 // *(Type<n>-1*)rhs[<n>-1]);
2459 // }
2460 //
2461 // ...
2462 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
2463 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2464 // RedList, reduce_func, &<lock>)) {
2465 // case 1:
2466 // ...
2467 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2468 // ...
2469 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2470 // break;
2471 // case 2:
2472 // ...
2473 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2474 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00002475 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002476 // break;
2477 // default:;
2478 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002479 //
2480 // if SimpleReduction is true, only the next code is generated:
2481 // ...
2482 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2483 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002484
2485 auto &C = CGM.getContext();
2486
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002487 if (SimpleReduction) {
2488 CodeGenFunction::RunCleanupsScope Scope(CGF);
2489 for (auto *E : ReductionOps) {
2490 CGF.EmitIgnoredExpr(E);
2491 }
2492 return;
2493 }
2494
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002495 // 1. Build a list of reduction variables.
2496 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2497 llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
2498 QualType ReductionArrayTy =
2499 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2500 /*IndexTypeQuals=*/0);
2501 auto *ReductionList =
2502 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2503 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
2504 auto *Elem = CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, ReductionList, I);
2505 CGF.Builder.CreateAlignedStore(
2506 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2507 CGF.EmitLValue(RHSExprs[I]).getAddress(), CGF.VoidPtrTy),
2508 Elem, CGM.PointerAlignInBytes);
2509 }
2510
2511 // 2. Emit reduce_func().
2512 auto *ReductionFn = emitReductionFunction(
2513 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
2514 RHSExprs, ReductionOps);
2515
2516 // 3. Create static kmp_critical_name lock = { 0 };
2517 auto *Lock = getCriticalRegionLock(".reduction");
2518
2519 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2520 // RedList, reduce_func, &<lock>);
2521 auto *IdentTLoc = emitUpdateLocation(
2522 CGF, Loc,
2523 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
2524 auto *ThreadId = getThreadID(CGF, Loc);
2525 auto *ReductionArrayTySize = llvm::ConstantInt::get(
2526 CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
2527 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList,
2528 CGF.VoidPtrTy);
2529 llvm::Value *Args[] = {
2530 IdentTLoc, // ident_t *<loc>
2531 ThreadId, // i32 <gtid>
2532 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
2533 ReductionArrayTySize, // size_type sizeof(RedList)
2534 RL, // void *RedList
2535 ReductionFn, // void (*) (void *, void *) <reduce_func>
2536 Lock // kmp_critical_name *&<lock>
2537 };
2538 auto Res = CGF.EmitRuntimeCall(
2539 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
2540 : OMPRTL__kmpc_reduce),
2541 Args);
2542
2543 // 5. Build switch(res)
2544 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2545 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
2546
2547 // 6. Build case 1:
2548 // ...
2549 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2550 // ...
2551 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2552 // break;
2553 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2554 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2555 CGF.EmitBlock(Case1BB);
2556
2557 {
2558 CodeGenFunction::RunCleanupsScope Scope(CGF);
2559 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2560 llvm::Value *EndArgs[] = {
2561 IdentTLoc, // ident_t *<loc>
2562 ThreadId, // i32 <gtid>
2563 Lock // kmp_critical_name *&<lock>
2564 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002565 CGF.EHStack
2566 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2567 NormalAndEHCleanup,
2568 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
2569 : OMPRTL__kmpc_end_reduce),
2570 llvm::makeArrayRef(EndArgs));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002571 for (auto *E : ReductionOps) {
2572 CGF.EmitIgnoredExpr(E);
2573 }
2574 }
2575
2576 CGF.EmitBranch(DefaultBB);
2577
2578 // 7. Build case 2:
2579 // ...
2580 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2581 // ...
2582 // break;
2583 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
2584 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
2585 CGF.EmitBlock(Case2BB);
2586
2587 {
2588 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00002589 if (!WithNowait) {
2590 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
2591 llvm::Value *EndArgs[] = {
2592 IdentTLoc, // ident_t *<loc>
2593 ThreadId, // i32 <gtid>
2594 Lock // kmp_critical_name *&<lock>
2595 };
2596 CGF.EHStack
2597 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2598 NormalAndEHCleanup,
2599 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
2600 llvm::makeArrayRef(EndArgs));
2601 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002602 auto I = LHSExprs.begin();
2603 for (auto *E : ReductionOps) {
2604 const Expr *XExpr = nullptr;
2605 const Expr *EExpr = nullptr;
2606 const Expr *UpExpr = nullptr;
2607 BinaryOperatorKind BO = BO_Comma;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002608 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2609 if (BO->getOpcode() == BO_Assign) {
2610 XExpr = BO->getLHS();
2611 UpExpr = BO->getRHS();
2612 }
2613 }
Alexey Bataev69a47792015-05-07 03:54:03 +00002614 // Try to emit update expression as a simple atomic.
2615 auto *RHSExpr = UpExpr;
2616 if (RHSExpr) {
2617 // Analyze RHS part of the whole expression.
2618 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
2619 RHSExpr->IgnoreParenImpCasts())) {
2620 // If this is a conditional operator, analyze its condition for
2621 // min/max reduction operator.
2622 RHSExpr = ACO->getCond();
2623 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002624 if (auto *BORHS =
Alexey Bataev69a47792015-05-07 03:54:03 +00002625 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002626 EExpr = BORHS->getRHS();
2627 BO = BORHS->getOpcode();
2628 }
2629 }
2630 if (XExpr) {
2631 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2632 LValue X = CGF.EmitLValue(XExpr);
2633 RValue E;
2634 if (EExpr)
2635 E = CGF.EmitAnyExpr(EExpr);
2636 CGF.EmitOMPAtomicSimpleUpdateExpr(
2637 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
2638 [&CGF, UpExpr, VD](RValue XRValue) {
2639 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
2640 PrivateScope.addPrivate(
2641 VD, [&CGF, VD, XRValue]() -> llvm::Value *{
2642 auto *LHSTemp = CGF.CreateMemTemp(VD->getType());
2643 CGF.EmitStoreThroughLValue(
2644 XRValue,
2645 CGF.MakeNaturalAlignAddrLValue(LHSTemp, VD->getType()));
2646 return LHSTemp;
2647 });
2648 (void)PrivateScope.Privatize();
2649 return CGF.EmitAnyExpr(UpExpr);
2650 });
2651 } else {
2652 // Emit as a critical region.
2653 emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
2654 CGF.EmitIgnoredExpr(E);
2655 }, Loc);
2656 }
2657 ++I;
2658 }
2659 }
2660
2661 CGF.EmitBranch(DefaultBB);
2662 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2663}
2664
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002665void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
2666 SourceLocation Loc) {
2667 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
2668 // global_tid);
2669 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2670 // Ignore return result until untied tasks are supported.
2671 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
2672}
2673
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002674void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
2675 const RegionCodeGenTy &CodeGen) {
2676 InlinedOpenMPRegionRAII Region(CGF, CodeGen);
2677 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002678}
2679