blob: b9ade9bda79323dbac27040359dfb44dc54e57a2 [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 Bataev18095712014-10-10 12:19:54 +0000285 CGF.CapturedStmtInfo = &CGInfo;
286 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 Bataev62b63b12015-03-10 07:28:44 +0000298 CGF.CapturedStmtInfo = &CGInfo;
299 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 Bataev9959db52014-05-06 10:08:46 +0000775 }
776 return RTLFn;
777}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000778
Alexander Musman21212e42015-03-13 10:38:23 +0000779llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
780 bool IVSigned) {
781 assert((IVSize == 32 || IVSize == 64) &&
782 "IV size is not compatible with the omp runtime");
783 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
784 : "__kmpc_for_static_init_4u")
785 : (IVSigned ? "__kmpc_for_static_init_8"
786 : "__kmpc_for_static_init_8u");
787 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
788 auto PtrTy = llvm::PointerType::getUnqual(ITy);
789 llvm::Type *TypeParams[] = {
790 getIdentTyPointerTy(), // loc
791 CGM.Int32Ty, // tid
792 CGM.Int32Ty, // schedtype
793 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
794 PtrTy, // p_lower
795 PtrTy, // p_upper
796 PtrTy, // p_stride
797 ITy, // incr
798 ITy // chunk
799 };
800 llvm::FunctionType *FnTy =
801 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
802 return CGM.CreateRuntimeFunction(FnTy, Name);
803}
804
Alexander Musman92bdaab2015-03-12 13:37:50 +0000805llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
806 bool IVSigned) {
807 assert((IVSize == 32 || IVSize == 64) &&
808 "IV size is not compatible with the omp runtime");
809 auto Name =
810 IVSize == 32
811 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
812 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
813 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
814 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
815 CGM.Int32Ty, // tid
816 CGM.Int32Ty, // schedtype
817 ITy, // lower
818 ITy, // upper
819 ITy, // stride
820 ITy // chunk
821 };
822 llvm::FunctionType *FnTy =
823 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
824 return CGM.CreateRuntimeFunction(FnTy, Name);
825}
826
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000827llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
828 bool IVSigned) {
829 assert((IVSize == 32 || IVSize == 64) &&
830 "IV size is not compatible with the omp runtime");
831 auto Name =
832 IVSize == 32
833 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
834 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
835 llvm::Type *TypeParams[] = {
836 getIdentTyPointerTy(), // loc
837 CGM.Int32Ty, // tid
838 };
839 llvm::FunctionType *FnTy =
840 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
841 return CGM.CreateRuntimeFunction(FnTy, Name);
842}
843
Alexander Musman92bdaab2015-03-12 13:37:50 +0000844llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
845 bool IVSigned) {
846 assert((IVSize == 32 || IVSize == 64) &&
847 "IV size is not compatible with the omp runtime");
848 auto Name =
849 IVSize == 32
850 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
851 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
852 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
853 auto PtrTy = llvm::PointerType::getUnqual(ITy);
854 llvm::Type *TypeParams[] = {
855 getIdentTyPointerTy(), // loc
856 CGM.Int32Ty, // tid
857 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
858 PtrTy, // p_lower
859 PtrTy, // p_upper
860 PtrTy // p_stride
861 };
862 llvm::FunctionType *FnTy =
863 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
864 return CGM.CreateRuntimeFunction(FnTy, Name);
865}
866
Alexey Bataev97720002014-11-11 04:05:39 +0000867llvm::Constant *
868CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
869 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000870 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +0000871 Twine(CGM.getMangledName(VD)) + ".cache.");
872}
873
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000874llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
875 const VarDecl *VD,
876 llvm::Value *VDAddr,
877 SourceLocation Loc) {
Alexey Bataev97720002014-11-11 04:05:39 +0000878 auto VarTy = VDAddr->getType()->getPointerElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000879 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev97720002014-11-11 04:05:39 +0000880 CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
881 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
882 getOrCreateThreadPrivateCache(VD)};
883 return CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000884 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000885}
886
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000887void CGOpenMPRuntime::emitThreadPrivateVarInit(
Alexey Bataev97720002014-11-11 04:05:39 +0000888 CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
889 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
890 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
891 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000892 auto OMPLoc = emitUpdateLocation(CGF, Loc);
893 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +0000894 OMPLoc);
895 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
896 // to register constructor/destructor for variable.
897 llvm::Value *Args[] = {OMPLoc,
898 CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
899 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000900 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000901 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +0000902}
903
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000904llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
Alexey Bataev97720002014-11-11 04:05:39 +0000905 const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
906 bool PerformInit, CodeGenFunction *CGF) {
907 VD = VD->getDefinition(CGM.getContext());
908 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
909 ThreadPrivateWithDefinition.insert(VD);
910 QualType ASTTy = VD->getType();
911
912 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
913 auto Init = VD->getAnyInitializer();
914 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
915 // Generate function that re-emits the declaration's initializer into the
916 // threadprivate copy of the variable VD
917 CodeGenFunction CtorCGF(CGM);
918 FunctionArgList Args;
919 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
920 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
921 Args.push_back(&Dst);
922
923 auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
924 CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
925 /*isVariadic=*/false);
926 auto FTy = CGM.getTypes().GetFunctionType(FI);
927 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
928 FTy, ".__kmpc_global_ctor_.", Loc);
929 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
930 Args, SourceLocation());
931 auto ArgVal = CtorCGF.EmitLoadOfScalar(
932 CtorCGF.GetAddrOfLocalVar(&Dst),
933 /*Volatile=*/false, CGM.PointerAlignInBytes,
934 CGM.getContext().VoidPtrTy, Dst.getLocation());
935 auto Arg = CtorCGF.Builder.CreatePointerCast(
936 ArgVal,
937 CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
938 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
939 /*IsInitializer=*/true);
940 ArgVal = CtorCGF.EmitLoadOfScalar(
941 CtorCGF.GetAddrOfLocalVar(&Dst),
942 /*Volatile=*/false, CGM.PointerAlignInBytes,
943 CGM.getContext().VoidPtrTy, Dst.getLocation());
944 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
945 CtorCGF.FinishFunction();
946 Ctor = Fn;
947 }
948 if (VD->getType().isDestructedType() != QualType::DK_none) {
949 // Generate function that emits destructor call for the threadprivate copy
950 // of the variable VD
951 CodeGenFunction DtorCGF(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().VoidTy, Args, FunctionType::ExtInfo(),
959 /*isVariadic=*/false);
960 auto FTy = CGM.getTypes().GetFunctionType(FI);
961 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
962 FTy, ".__kmpc_global_dtor_.", Loc);
963 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
964 SourceLocation());
965 auto ArgVal = DtorCGF.EmitLoadOfScalar(
966 DtorCGF.GetAddrOfLocalVar(&Dst),
967 /*Volatile=*/false, CGM.PointerAlignInBytes,
968 CGM.getContext().VoidPtrTy, Dst.getLocation());
969 DtorCGF.emitDestroy(ArgVal, ASTTy,
970 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
971 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
972 DtorCGF.FinishFunction();
973 Dtor = Fn;
974 }
975 // Do not emit init function if it is not required.
976 if (!Ctor && !Dtor)
977 return nullptr;
978
979 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
980 auto CopyCtorTy =
981 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
982 /*isVarArg=*/false)->getPointerTo();
983 // Copying constructor for the threadprivate variable.
984 // Must be NULL - reserved by runtime, but currently it requires that this
985 // parameter is always NULL. Otherwise it fires assertion.
986 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
987 if (Ctor == nullptr) {
988 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
989 /*isVarArg=*/false)->getPointerTo();
990 Ctor = llvm::Constant::getNullValue(CtorTy);
991 }
992 if (Dtor == nullptr) {
993 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
994 /*isVarArg=*/false)->getPointerTo();
995 Dtor = llvm::Constant::getNullValue(DtorTy);
996 }
997 if (!CGF) {
998 auto InitFunctionTy =
999 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1000 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1001 InitFunctionTy, ".__omp_threadprivate_init_.");
1002 CodeGenFunction InitCGF(CGM);
1003 FunctionArgList ArgList;
1004 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1005 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1006 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001007 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001008 InitCGF.FinishFunction();
1009 return InitFunction;
1010 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001011 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001012 }
1013 return nullptr;
1014}
1015
Alexey Bataev1d677132015-04-22 13:57:31 +00001016/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1017/// function. Here is the logic:
1018/// if (Cond) {
1019/// ThenGen();
1020/// } else {
1021/// ElseGen();
1022/// }
1023static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1024 const RegionCodeGenTy &ThenGen,
1025 const RegionCodeGenTy &ElseGen) {
1026 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1027
1028 // If the condition constant folds and can be elided, try to avoid emitting
1029 // the condition and the dead arm of the if/else.
1030 bool CondConstant;
1031 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1032 CodeGenFunction::RunCleanupsScope Scope(CGF);
1033 if (CondConstant) {
1034 ThenGen(CGF);
1035 } else {
1036 ElseGen(CGF);
1037 }
1038 return;
1039 }
1040
1041 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1042 // emit the conditional branch.
1043 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1044 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1045 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1046 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1047
1048 // Emit the 'then' code.
1049 CGF.EmitBlock(ThenBlock);
1050 {
1051 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1052 ThenGen(CGF);
1053 }
1054 CGF.EmitBranch(ContBlock);
1055 // Emit the 'else' code if present.
1056 {
1057 // There is no need to emit line number for unconditional branch.
1058 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1059 CGF.EmitBlock(ElseBlock);
1060 }
1061 {
1062 CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1063 ElseGen(CGF);
1064 }
1065 {
1066 // There is no need to emit line number for unconditional branch.
1067 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1068 CGF.EmitBranch(ContBlock);
1069 }
1070 // Emit the continuation block for code after the if.
1071 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001072}
1073
Alexey Bataev1d677132015-04-22 13:57:31 +00001074void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1075 llvm::Value *OutlinedFn,
1076 llvm::Value *CapturedStruct,
1077 const Expr *IfCond) {
1078 auto *RTLoc = emitUpdateLocation(CGF, Loc);
1079 auto &&ThenGen =
1080 [this, OutlinedFn, CapturedStruct, RTLoc](CodeGenFunction &CGF) {
1081 // Build call __kmpc_fork_call(loc, 1, microtask,
1082 // captured_struct/*context*/)
1083 llvm::Value *Args[] = {
1084 RTLoc,
1085 CGF.Builder.getInt32(
1086 1), // Number of arguments after 'microtask' argument
1087 // (there is only one additional argument - 'context')
1088 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
1089 CGF.EmitCastToVoidPtr(CapturedStruct)};
1090 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1091 CGF.EmitRuntimeCall(RTLFn, Args);
1092 };
1093 auto &&ElseGen = [this, OutlinedFn, CapturedStruct, RTLoc, Loc](
1094 CodeGenFunction &CGF) {
1095 auto ThreadID = getThreadID(CGF, Loc);
1096 // Build calls:
1097 // __kmpc_serialized_parallel(&Loc, GTid);
1098 llvm::Value *Args[] = {RTLoc, ThreadID};
1099 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1100 Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001101
Alexey Bataev1d677132015-04-22 13:57:31 +00001102 // OutlinedFn(&GTid, &zero, CapturedStruct);
1103 auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1104 auto Int32Ty = CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32,
1105 /*Signed*/ true);
1106 auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
1107 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1108 llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
1109 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001110
Alexey Bataev1d677132015-04-22 13:57:31 +00001111 // __kmpc_end_serialized_parallel(&Loc, GTid);
1112 llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1113 CGF.EmitRuntimeCall(
1114 createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1115 };
1116 if (IfCond) {
1117 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1118 } else {
1119 CodeGenFunction::RunCleanupsScope Scope(CGF);
1120 ThenGen(CGF);
1121 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001122}
1123
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001124// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001125// thread-ID variable (it is passed in a first argument of the outlined function
1126// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1127// regular serial code region, get thread ID by calling kmp_int32
1128// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1129// return the address of that temp.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001130llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
Alexey Bataevd74d0602014-10-13 06:02:40 +00001131 SourceLocation Loc) {
1132 if (auto OMPRegionInfo =
1133 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001134 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001135 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001136
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001137 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001138 auto Int32Ty =
1139 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1140 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1141 CGF.EmitStoreOfScalar(ThreadID,
1142 CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
1143
1144 return ThreadIDTemp;
1145}
1146
Alexey Bataev97720002014-11-11 04:05:39 +00001147llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001148CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001149 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001150 SmallString<256> Buffer;
1151 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001152 Out << Name;
1153 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001154 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1155 if (Elem.second) {
1156 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001157 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001158 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001159 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001160
David Blaikie13156b62014-11-19 03:06:06 +00001161 return Elem.second = new llvm::GlobalVariable(
1162 CGM.getModule(), Ty, /*IsConstant*/ false,
1163 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1164 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001165}
1166
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001167llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001168 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001169 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001170}
1171
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001172namespace {
Alexey Bataeva744ff52015-05-05 09:24:37 +00001173template <size_t N> class CallEndCleanup : public EHScopeStack::Cleanup {
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001174 llvm::Value *Callee;
Alexey Bataeva744ff52015-05-05 09:24:37 +00001175 llvm::Value *Args[N];
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001176
1177public:
Alexey Bataeva744ff52015-05-05 09:24:37 +00001178 CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1179 : Callee(Callee) {
1180 assert(CleanupArgs.size() == N);
1181 std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1182 }
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001183 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1184 CGF.EmitRuntimeCall(Callee, Args);
1185 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001186};
1187} // namespace
1188
1189void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1190 StringRef CriticalName,
1191 const RegionCodeGenTy &CriticalOpGen,
1192 SourceLocation Loc) {
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001193 // __kmpc_critical(ident_t *, gtid, Lock);
1194 // CriticalOpGen();
1195 // __kmpc_end_critical(ident_t *, gtid, Lock);
1196 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001197 {
1198 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001199 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1200 getCriticalRegionLock(CriticalName)};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001201 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001202 // Build a call to __kmpc_end_critical
Alexey Bataeva744ff52015-05-05 09:24:37 +00001203 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001204 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1205 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001206 emitInlinedDirective(CGF, CriticalOpGen);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001207 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001208}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001209
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001210static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001211 const RegionCodeGenTy &BodyOpGen) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001212 llvm::Value *CallBool = CGF.EmitScalarConversion(
1213 IfCond,
1214 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
1215 CGF.getContext().BoolTy);
1216
1217 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1218 auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1219 // Generate the branch (If-stmt)
1220 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1221 CGF.EmitBlock(ThenBlock);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001222 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, BodyOpGen);
Alexey Bataev8d690652014-12-04 07:23:53 +00001223 // Emit the rest of bblocks/branches
1224 CGF.EmitBranch(ContBlock);
1225 CGF.EmitBlock(ContBlock, true);
1226}
1227
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001228void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001229 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001230 SourceLocation Loc) {
Alexey Bataev8d690652014-12-04 07:23:53 +00001231 // if(__kmpc_master(ident_t *, gtid)) {
1232 // MasterOpGen();
1233 // __kmpc_end_master(ident_t *, gtid);
1234 // }
1235 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001236 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001237 auto *IsMaster =
1238 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001239 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1240 MasterCallEndCleanup;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001241 emitIfStmt(CGF, IsMaster, [&](CodeGenFunction &CGF) -> void {
1242 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001243 CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001244 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1245 llvm::makeArrayRef(Args));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001246 MasterOpGen(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00001247 });
1248}
1249
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001250void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1251 SourceLocation Loc) {
Alexey Bataev9f797f32015-02-05 05:57:51 +00001252 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1253 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001254 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00001255 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001256 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev9f797f32015-02-05 05:57:51 +00001257}
1258
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001259void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1260 const RegionCodeGenTy &TaskgroupOpGen,
1261 SourceLocation Loc) {
1262 // __kmpc_taskgroup(ident_t *, gtid);
1263 // TaskgroupOpGen();
1264 // __kmpc_end_taskgroup(ident_t *, gtid);
1265 // Prepare arguments and build a call to __kmpc_taskgroup
1266 {
1267 CodeGenFunction::RunCleanupsScope Scope(CGF);
1268 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1269 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1270 // Build a call to __kmpc_end_taskgroup
1271 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1272 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1273 llvm::makeArrayRef(Args));
1274 emitInlinedDirective(CGF, TaskgroupOpGen);
1275 }
1276}
1277
Alexey Bataeva63048e2015-03-23 06:18:07 +00001278static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00001279 CodeGenModule &CGM, llvm::Type *ArgsType,
1280 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1281 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001282 auto &C = CGM.getContext();
1283 // void copy_func(void *LHSArg, void *RHSArg);
1284 FunctionArgList Args;
1285 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1286 C.VoidPtrTy);
1287 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1288 C.VoidPtrTy);
1289 Args.push_back(&LHSArg);
1290 Args.push_back(&RHSArg);
1291 FunctionType::ExtInfo EI;
1292 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1293 C.VoidTy, Args, EI, /*isVariadic=*/false);
1294 auto *Fn = llvm::Function::Create(
1295 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1296 ".omp.copyprivate.copy_func", &CGM.getModule());
1297 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
1298 CodeGenFunction CGF(CGM);
1299 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00001300 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001301 // Src = (void*[n])(RHSArg);
1302 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1303 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
1304 CGF.PointerAlignInBytes),
1305 ArgsType);
1306 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1307 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
1308 CGF.PointerAlignInBytes),
1309 ArgsType);
1310 // *(Type0*)Dst[0] = *(Type0*)Src[0];
1311 // *(Type1*)Dst[1] = *(Type1*)Src[1];
1312 // ...
1313 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00001314 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataev420d45b2015-04-14 05:11:24 +00001315 auto *DestAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1316 CGF.Builder.CreateAlignedLoad(
1317 CGF.Builder.CreateStructGEP(nullptr, LHS, I),
1318 CGM.PointerAlignInBytes),
1319 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
1320 auto *SrcAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1321 CGF.Builder.CreateAlignedLoad(
1322 CGF.Builder.CreateStructGEP(nullptr, RHS, I),
1323 CGM.PointerAlignInBytes),
1324 CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001325 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1326 QualType Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001327 CGF.EmitOMPCopy(CGF, Type, DestAddr, SrcAddr,
Alexey Bataev420d45b2015-04-14 05:11:24 +00001328 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()),
1329 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
1330 AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001331 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001332 CGF.FinishFunction();
1333 return Fn;
1334}
1335
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001336void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001337 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001338 SourceLocation Loc,
1339 ArrayRef<const Expr *> CopyprivateVars,
1340 ArrayRef<const Expr *> SrcExprs,
1341 ArrayRef<const Expr *> DstExprs,
1342 ArrayRef<const Expr *> AssignmentOps) {
1343 assert(CopyprivateVars.size() == SrcExprs.size() &&
1344 CopyprivateVars.size() == DstExprs.size() &&
1345 CopyprivateVars.size() == AssignmentOps.size());
1346 auto &C = CGM.getContext();
1347 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001348 // if(__kmpc_single(ident_t *, gtid)) {
1349 // SingleOpGen();
1350 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001351 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001352 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001353 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1354 // <copy_func>, did_it);
1355
1356 llvm::AllocaInst *DidIt = nullptr;
1357 if (!CopyprivateVars.empty()) {
1358 // int32 did_it = 0;
1359 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1360 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
Alexey Bataev66beaa92015-04-30 03:47:32 +00001361 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(0), DidIt,
1362 DidIt->getAlignment());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001363 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001364 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00001365 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001366 auto *IsSingle =
1367 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001368 typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1369 SingleCallEndCleanup;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001370 emitIfStmt(CGF, IsSingle, [&](CodeGenFunction &CGF) -> void {
1371 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataeva744ff52015-05-05 09:24:37 +00001372 CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001373 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
1374 llvm::makeArrayRef(Args));
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001375 SingleOpGen(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001376 if (DidIt) {
1377 // did_it = 1;
1378 CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
1379 DidIt->getAlignment());
1380 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001381 });
Alexey Bataeva63048e2015-03-23 06:18:07 +00001382 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
1383 // <copy_func>, did_it);
1384 if (DidIt) {
1385 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
1386 auto CopyprivateArrayTy =
1387 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
1388 /*IndexTypeQuals=*/0);
1389 // Create a list of all private variables for copyprivate.
1390 auto *CopyprivateList =
1391 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
1392 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001393 auto *Elem = CGF.Builder.CreateStructGEP(
1394 CopyprivateList->getAllocatedType(), CopyprivateList, I);
Alexey Bataeva63048e2015-03-23 06:18:07 +00001395 CGF.Builder.CreateAlignedStore(
1396 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1397 CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
1398 Elem, CGM.PointerAlignInBytes);
1399 }
1400 // Build function that copies private values from single region to all other
1401 // threads in the corresponding parallel region.
1402 auto *CpyFn = emitCopyprivateCopyFunction(
1403 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001404 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001405 auto *BufSize = llvm::ConstantInt::get(
1406 CGM.SizeTy, C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001407 auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
1408 CGF.VoidPtrTy);
1409 auto *DidItVal =
1410 CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
1411 llvm::Value *Args[] = {
1412 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
1413 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00001414 BufSize, // size_t <buf_size>
Alexey Bataeva63048e2015-03-23 06:18:07 +00001415 CL, // void *<copyprivate list>
1416 CpyFn, // void (*) (void *, void *) <copy_func>
1417 DidItVal // i32 did_it
1418 };
1419 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
1420 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001421}
1422
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001423void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
1424 const RegionCodeGenTy &OrderedOpGen,
1425 SourceLocation Loc) {
1426 // __kmpc_ordered(ident_t *, gtid);
1427 // OrderedOpGen();
1428 // __kmpc_end_ordered(ident_t *, gtid);
1429 // Prepare arguments and build a call to __kmpc_ordered
1430 {
1431 CodeGenFunction::RunCleanupsScope Scope(CGF);
1432 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1433 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
1434 // Build a call to __kmpc_end_ordered
Alexey Bataeva744ff52015-05-05 09:24:37 +00001435 CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001436 NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
1437 llvm::makeArrayRef(Args));
1438 emitInlinedDirective(CGF, OrderedOpGen);
1439 }
1440}
1441
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001442void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf2685682015-03-30 04:30:22 +00001443 OpenMPDirectiveKind Kind) {
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001444 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataevf2685682015-03-30 04:30:22 +00001445 OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
1446 if (Kind == OMPD_for) {
1447 Flags =
1448 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
1449 } else if (Kind == OMPD_sections) {
1450 Flags = static_cast<OpenMPLocationFlags>(Flags |
1451 OMP_IDENT_BARRIER_IMPL_SECTIONS);
1452 } else if (Kind == OMPD_single) {
1453 Flags =
1454 static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
1455 } else if (Kind == OMPD_barrier) {
1456 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
1457 } else {
1458 Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
1459 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001460 // Build call __kmpc_cancel_barrier(loc, thread_id);
1461 // Replace __kmpc_barrier() function by __kmpc_cancel_barrier() because this
1462 // one provides the same functionality and adds initial support for
1463 // cancellation constructs introduced in OpenMP 4.0. __kmpc_cancel_barrier()
1464 // is provided default by the runtime library so it safe to make such
1465 // replacement.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001466 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1467 getThreadID(CGF, Loc)};
1468 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001469}
1470
Alexander Musmanc6388682014-12-15 07:07:06 +00001471/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
1472/// the enum sched_type in kmp.h).
1473enum OpenMPSchedType {
1474 /// \brief Lower bound for default (unordered) versions.
1475 OMP_sch_lower = 32,
1476 OMP_sch_static_chunked = 33,
1477 OMP_sch_static = 34,
1478 OMP_sch_dynamic_chunked = 35,
1479 OMP_sch_guided_chunked = 36,
1480 OMP_sch_runtime = 37,
1481 OMP_sch_auto = 38,
1482 /// \brief Lower bound for 'ordered' versions.
1483 OMP_ord_lower = 64,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001484 OMP_ord_static_chunked = 65,
1485 OMP_ord_static = 66,
1486 OMP_ord_dynamic_chunked = 67,
1487 OMP_ord_guided_chunked = 68,
1488 OMP_ord_runtime = 69,
1489 OMP_ord_auto = 70,
1490 OMP_sch_default = OMP_sch_static,
Alexander Musmanc6388682014-12-15 07:07:06 +00001491};
1492
1493/// \brief Map the OpenMP loop schedule to the runtime enumeration.
1494static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001495 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001496 switch (ScheduleKind) {
1497 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001498 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
1499 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00001500 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001501 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001502 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001503 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00001504 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001505 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
1506 case OMPC_SCHEDULE_auto:
1507 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00001508 case OMPC_SCHEDULE_unknown:
1509 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001510 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00001511 }
1512 llvm_unreachable("Unexpected runtime schedule");
1513}
1514
1515bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1516 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001517 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00001518 return Schedule == OMP_sch_static;
1519}
1520
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001521bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001522 auto Schedule =
1523 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001524 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
1525 return Schedule != OMP_sch_static;
1526}
1527
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001528void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
1529 OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001530 unsigned IVSize, bool IVSigned, bool Ordered,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001531 llvm::Value *IL, llvm::Value *LB,
1532 llvm::Value *UB, llvm::Value *ST,
1533 llvm::Value *Chunk) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001534 OpenMPSchedType Schedule =
1535 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
1536 if (Ordered ||
1537 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
1538 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked)) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00001539 // Call __kmpc_dispatch_init(
1540 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
1541 // kmp_int[32|64] lower, kmp_int[32|64] upper,
1542 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00001543
Alexander Musman92bdaab2015-03-12 13:37:50 +00001544 // If the Chunk was not specified in the clause - use default value 1.
1545 if (Chunk == nullptr)
1546 Chunk = CGF.Builder.getIntN(IVSize, 1);
1547 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1548 getThreadID(CGF, Loc),
1549 CGF.Builder.getInt32(Schedule), // Schedule type
1550 CGF.Builder.getIntN(IVSize, 0), // Lower
1551 UB, // Upper
1552 CGF.Builder.getIntN(IVSize, 1), // Stride
1553 Chunk // Chunk
1554 };
1555 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
1556 } else {
1557 // Call __kmpc_for_static_init(
1558 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
1559 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
1560 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
1561 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
1562 if (Chunk == nullptr) {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001563 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
Alexander Musman92bdaab2015-03-12 13:37:50 +00001564 "expected static non-chunked schedule");
1565 // If the Chunk was not specified in the clause - use default value 1.
1566 Chunk = CGF.Builder.getIntN(IVSize, 1);
1567 } else
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001568 assert((Schedule == OMP_sch_static_chunked ||
1569 Schedule == OMP_ord_static_chunked) &&
Alexander Musman92bdaab2015-03-12 13:37:50 +00001570 "expected static chunked schedule");
1571 llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1572 getThreadID(CGF, Loc),
1573 CGF.Builder.getInt32(Schedule), // Schedule type
1574 IL, // &isLastIter
1575 LB, // &LB
1576 UB, // &UB
1577 ST, // &Stride
1578 CGF.Builder.getIntN(IVSize, 1), // Incr
1579 Chunk // Chunk
1580 };
Alexander Musman21212e42015-03-13 10:38:23 +00001581 CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
Alexander Musman92bdaab2015-03-12 13:37:50 +00001582 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001583}
1584
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001585void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
1586 SourceLocation Loc) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001587 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001588 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1589 getThreadID(CGF, Loc)};
1590 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
1591 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00001592}
1593
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001594void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
1595 SourceLocation Loc,
1596 unsigned IVSize,
1597 bool IVSigned) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001598 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
1599 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
1600 getThreadID(CGF, Loc)};
1601 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
1602}
1603
Alexander Musman92bdaab2015-03-12 13:37:50 +00001604llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
1605 SourceLocation Loc, unsigned IVSize,
1606 bool IVSigned, llvm::Value *IL,
1607 llvm::Value *LB, llvm::Value *UB,
1608 llvm::Value *ST) {
1609 // Call __kmpc_dispatch_next(
1610 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1611 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1612 // kmp_int[32|64] *p_stride);
1613 llvm::Value *Args[] = {
1614 emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
1615 IL, // &isLastIter
1616 LB, // &Lower
1617 UB, // &Upper
1618 ST // &Stride
1619 };
1620 llvm::Value *Call =
1621 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
1622 return CGF.EmitScalarConversion(
1623 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
1624 CGF.getContext().BoolTy);
1625}
1626
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001627void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
1628 llvm::Value *NumThreads,
1629 SourceLocation Loc) {
Alexey Bataevb2059782014-10-13 08:23:51 +00001630 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
1631 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001632 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00001633 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001634 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
1635 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00001636}
1637
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001638void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
1639 SourceLocation Loc) {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001640 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001641 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
1642 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001643}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001644
Alexey Bataev62b63b12015-03-10 07:28:44 +00001645namespace {
1646/// \brief Indexes of fields for type kmp_task_t.
1647enum KmpTaskTFields {
1648 /// \brief List of shared variables.
1649 KmpTaskTShareds,
1650 /// \brief Task routine.
1651 KmpTaskTRoutine,
1652 /// \brief Partition id for the untied tasks.
1653 KmpTaskTPartId,
1654 /// \brief Function with call of destructors for private variables.
1655 KmpTaskTDestructors,
1656};
1657} // namespace
1658
1659void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
1660 if (!KmpRoutineEntryPtrTy) {
1661 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
1662 auto &C = CGM.getContext();
1663 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
1664 FunctionProtoType::ExtProtoInfo EPI;
1665 KmpRoutineEntryPtrQTy = C.getPointerType(
1666 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
1667 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
1668 }
1669}
1670
1671static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1672 QualType FieldTy) {
1673 auto *Field = FieldDecl::Create(
1674 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1675 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1676 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1677 Field->setAccess(AS_public);
1678 DC->addDecl(Field);
1679}
1680
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001681namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00001682struct PrivateHelpersTy {
1683 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
1684 const VarDecl *PrivateElemInit)
1685 : Original(Original), PrivateCopy(PrivateCopy),
1686 PrivateElemInit(PrivateElemInit) {}
1687 const VarDecl *Original;
1688 const VarDecl *PrivateCopy;
1689 const VarDecl *PrivateElemInit;
1690};
1691typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001692} // namespace
1693
Alexey Bataev9e034042015-05-05 04:05:12 +00001694static RecordDecl *
1695createPrivatesRecordDecl(CodeGenModule &CGM,
1696 const ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001697 if (!Privates.empty()) {
1698 auto &C = CGM.getContext();
1699 // Build struct .kmp_privates_t. {
1700 // /* private vars */
1701 // };
1702 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
1703 RD->startDefinition();
1704 for (auto &&Pair : Privates) {
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001705 auto Type = Pair.second.Original->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00001706 Type = Type.getNonReferenceType();
1707 addFieldToRecordDecl(C, RD, Type);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001708 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001709 RD->completeDefinition();
1710 return RD;
1711 }
1712 return nullptr;
1713}
1714
Alexey Bataev9e034042015-05-05 04:05:12 +00001715static RecordDecl *
1716createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001717 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001718 auto &C = CGM.getContext();
1719 // Build struct kmp_task_t {
1720 // void * shareds;
1721 // kmp_routine_entry_t routine;
1722 // kmp_int32 part_id;
1723 // kmp_routine_entry_t destructors;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001724 // };
1725 auto *RD = C.buildImplicitRecord("kmp_task_t");
1726 RD->startDefinition();
1727 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1728 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
1729 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1730 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001731 RD->completeDefinition();
1732 return RD;
1733}
1734
1735static RecordDecl *
1736createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
1737 const ArrayRef<PrivateDataTy> Privates) {
1738 auto &C = CGM.getContext();
1739 // Build struct kmp_task_t_with_privates {
1740 // kmp_task_t task_data;
1741 // .kmp_privates_t. privates;
1742 // };
1743 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
1744 RD->startDefinition();
1745 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001746 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
1747 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
1748 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001749 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001750 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001751}
1752
1753/// \brief Emit a proxy function which accepts kmp_task_t as the second
1754/// argument.
1755/// \code
1756/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001757/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
1758/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001759/// return 0;
1760/// }
1761/// \endcode
1762static llvm::Value *
1763emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001764 QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
1765 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001766 QualType SharedsPtrTy, llvm::Value *TaskFunction,
1767 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001768 auto &C = CGM.getContext();
1769 FunctionArgList Args;
1770 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1771 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001772 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001773 Args.push_back(&GtidArg);
1774 Args.push_back(&TaskTypeArg);
1775 FunctionType::ExtInfo Info;
1776 auto &TaskEntryFnInfo =
1777 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1778 /*isVariadic=*/false);
1779 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
1780 auto *TaskEntry =
1781 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
1782 ".omp_task_entry.", &CGM.getModule());
1783 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
1784 CodeGenFunction CGF(CGM);
1785 CGF.disableDebugInfo();
1786 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
1787
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001788 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
1789 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001790 auto *GtidParam = CGF.EmitLoadOfScalar(
1791 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
1792 C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001793 auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
1794 CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001795 LValue TDBase =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001796 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
1797 auto *KmpTaskTWithPrivatesQTyRD =
1798 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001799 LValue Base =
1800 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001801 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
1802 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
1803 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
1804 auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
1805
1806 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
1807 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001808 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001809 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001810 CGF.ConvertTypeForMem(SharedsPtrTy));
1811
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001812 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
1813 llvm::Value *PrivatesParam;
1814 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
1815 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
1816 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1817 PrivatesLVal.getAddress(), CGF.VoidPtrTy);
1818 } else {
1819 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
1820 }
1821
1822 llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
1823 TaskPrivatesMap, SharedsParam};
Alexey Bataev62b63b12015-03-10 07:28:44 +00001824 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
1825 CGF.EmitStoreThroughLValue(
1826 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
1827 CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
1828 CGF.FinishFunction();
1829 return TaskEntry;
1830}
1831
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001832static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
1833 SourceLocation Loc,
1834 QualType KmpInt32Ty,
1835 QualType KmpTaskTWithPrivatesPtrQTy,
1836 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001837 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001838 FunctionArgList Args;
1839 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
1840 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001841 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001842 Args.push_back(&GtidArg);
1843 Args.push_back(&TaskTypeArg);
1844 FunctionType::ExtInfo Info;
1845 auto &DestructorFnInfo =
1846 CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
1847 /*isVariadic=*/false);
1848 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
1849 auto *DestructorFn =
1850 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
1851 ".omp_task_destructor.", &CGM.getModule());
1852 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, DestructorFnInfo, DestructorFn);
1853 CodeGenFunction CGF(CGM);
1854 CGF.disableDebugInfo();
1855 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
1856 Args);
1857
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00001858 auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
1859 CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
1860 LValue Base =
1861 CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
1862 auto *KmpTaskTWithPrivatesQTyRD =
1863 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
1864 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001865 Base = CGF.EmitLValueForField(Base, *FI);
1866 for (auto *Field :
1867 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
1868 if (auto DtorKind = Field->getType().isDestructedType()) {
1869 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
1870 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
1871 }
1872 }
1873 CGF.FinishFunction();
1874 return DestructorFn;
1875}
1876
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001877/// \brief Emit a privates mapping function for correct handling of private and
1878/// firstprivate variables.
1879/// \code
1880/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
1881/// **noalias priv1,..., <tyn> **noalias privn) {
1882/// *priv1 = &.privates.priv1;
1883/// ...;
1884/// *privn = &.privates.privn;
1885/// }
1886/// \endcode
1887static llvm::Value *
1888emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
1889 const ArrayRef<const Expr *> PrivateVars,
1890 const ArrayRef<const Expr *> FirstprivateVars,
1891 QualType PrivatesQTy,
1892 const ArrayRef<PrivateDataTy> Privates) {
1893 auto &C = CGM.getContext();
1894 FunctionArgList Args;
1895 ImplicitParamDecl TaskPrivatesArg(
1896 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1897 C.getPointerType(PrivatesQTy).withConst().withRestrict());
1898 Args.push_back(&TaskPrivatesArg);
1899 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
1900 unsigned Counter = 1;
1901 for (auto *E: PrivateVars) {
1902 Args.push_back(ImplicitParamDecl::Create(
1903 C, /*DC=*/nullptr, Loc,
1904 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
1905 .withConst()
1906 .withRestrict()));
1907 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1908 PrivateVarsPos[VD] = Counter;
1909 ++Counter;
1910 }
1911 for (auto *E : FirstprivateVars) {
1912 Args.push_back(ImplicitParamDecl::Create(
1913 C, /*DC=*/nullptr, Loc,
1914 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
1915 .withConst()
1916 .withRestrict()));
1917 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1918 PrivateVarsPos[VD] = Counter;
1919 ++Counter;
1920 }
1921 FunctionType::ExtInfo Info;
1922 auto &TaskPrivatesMapFnInfo =
1923 CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
1924 /*isVariadic=*/false);
1925 auto *TaskPrivatesMapTy =
1926 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
1927 auto *TaskPrivatesMap = llvm::Function::Create(
1928 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
1929 ".omp_task_privates_map.", &CGM.getModule());
1930 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskPrivatesMapFnInfo,
1931 TaskPrivatesMap);
1932 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
1933 CodeGenFunction CGF(CGM);
1934 CGF.disableDebugInfo();
1935 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
1936 TaskPrivatesMapFnInfo, Args);
1937
1938 // *privi = &.privates.privi;
1939 auto *TaskPrivatesArgAddr = CGF.Builder.CreateAlignedLoad(
1940 CGF.GetAddrOfLocalVar(&TaskPrivatesArg), CGM.PointerAlignInBytes);
1941 LValue Base =
1942 CGF.MakeNaturalAlignAddrLValue(TaskPrivatesArgAddr, PrivatesQTy);
1943 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
1944 Counter = 0;
1945 for (auto *Field : PrivatesQTyRD->fields()) {
1946 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
1947 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
1948 auto RefLVal = CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(VD),
1949 VD->getType());
1950 auto RefLoadRVal = CGF.EmitLoadOfLValue(RefLVal, Loc);
1951 CGF.EmitStoreOfScalar(
1952 FieldLVal.getAddress(),
1953 CGF.MakeNaturalAlignAddrLValue(RefLoadRVal.getScalarVal(),
1954 RefLVal.getType()->getPointeeType()));
1955 ++Counter;
1956 }
1957 CGF.FinishFunction();
1958 return TaskPrivatesMap;
1959}
1960
Alexey Bataev9e034042015-05-05 04:05:12 +00001961static int array_pod_sort_comparator(const PrivateDataTy *P1,
1962 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001963 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
1964}
1965
1966void CGOpenMPRuntime::emitTaskCall(
1967 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
1968 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
1969 llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds,
1970 const Expr *IfCond, const ArrayRef<const Expr *> PrivateVars,
Alexey Bataev9e034042015-05-05 04:05:12 +00001971 const ArrayRef<const Expr *> PrivateCopies,
1972 const ArrayRef<const Expr *> FirstprivateVars,
1973 const ArrayRef<const Expr *> FirstprivateCopies,
1974 const ArrayRef<const Expr *> FirstprivateInits) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001975 auto &C = CGM.getContext();
Alexey Bataev9e034042015-05-05 04:05:12 +00001976 llvm::SmallVector<PrivateDataTy, 8> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001977 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00001978 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001979 for (auto *E : PrivateVars) {
1980 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1981 Privates.push_back(std::make_pair(
1982 C.getTypeAlignInChars(VD->getType()),
Alexey Bataev9e034042015-05-05 04:05:12 +00001983 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
1984 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001985 ++I;
1986 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001987 I = FirstprivateCopies.begin();
1988 auto IElemInitRef = FirstprivateInits.begin();
1989 for (auto *E : FirstprivateVars) {
1990 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1991 Privates.push_back(std::make_pair(
1992 C.getTypeAlignInChars(VD->getType()),
1993 PrivateHelpersTy(
1994 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
1995 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
1996 ++I, ++IElemInitRef;
1997 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001998 llvm::array_pod_sort(Privates.begin(), Privates.end(),
1999 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002000 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2001 // Build type kmp_routine_entry_t (if not built yet).
2002 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002003 // Build type kmp_task_t (if not built yet).
2004 if (KmpTaskTQTy.isNull()) {
2005 KmpTaskTQTy = C.getRecordType(
2006 createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
2007 }
2008 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002009 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002010 auto *KmpTaskTWithPrivatesQTyRD =
2011 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
2012 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
2013 QualType KmpTaskTWithPrivatesPtrQTy =
2014 C.getPointerType(KmpTaskTWithPrivatesQTy);
2015 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
2016 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
2017 auto KmpTaskTWithPrivatesTySize =
2018 CGM.getSize(C.getTypeSizeInChars(KmpTaskTWithPrivatesQTy));
Alexey Bataev62b63b12015-03-10 07:28:44 +00002019 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
2020
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002021 // Emit initial values for private copies (if any).
2022 llvm::Value *TaskPrivatesMap = nullptr;
2023 auto *TaskPrivatesMapTy =
2024 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
2025 3)
2026 ->getType();
2027 if (!Privates.empty()) {
2028 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2029 TaskPrivatesMap = emitTaskPrivateMappingFunction(
2030 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
2031 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2032 TaskPrivatesMap, TaskPrivatesMapTy);
2033 } else {
2034 TaskPrivatesMap = llvm::ConstantPointerNull::get(
2035 cast<llvm::PointerType>(TaskPrivatesMapTy));
2036 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002037 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
2038 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002039 auto *TaskEntry = emitProxyTaskFunction(
2040 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002041 KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002042
2043 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
2044 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2045 // kmp_routine_entry_t *task_entry);
2046 // Task flags. Format is taken from
2047 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
2048 // description of kmp_tasking_flags struct.
2049 const unsigned TiedFlag = 0x1;
2050 const unsigned FinalFlag = 0x2;
2051 unsigned Flags = Tied ? TiedFlag : 0;
2052 auto *TaskFlags =
2053 Final.getPointer()
2054 ? CGF.Builder.CreateSelect(Final.getPointer(),
2055 CGF.Builder.getInt32(FinalFlag),
2056 CGF.Builder.getInt32(/*C=*/0))
2057 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
2058 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
2059 auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002060 llvm::Value *AllocArgs[] = {
2061 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), TaskFlags,
2062 KmpTaskTWithPrivatesTySize, CGM.getSize(SharedsSize),
2063 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskEntry,
2064 KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00002065 auto *NewTask = CGF.EmitRuntimeCall(
2066 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002067 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2068 NewTask, KmpTaskTWithPrivatesPtrTy);
2069 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
2070 KmpTaskTWithPrivatesQTy);
2071 LValue TDBase =
2072 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00002073 // Fill the data in the resulting kmp_task_t record.
2074 // Copy shareds if there are any.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002075 llvm::Value *KmpTaskSharedsPtr = nullptr;
2076 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
2077 KmpTaskSharedsPtr = CGF.EmitLoadOfScalar(
2078 CGF.EmitLValueForField(
2079 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)),
2080 Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002081 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002082 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002083 // Emit initial values for private copies (if any).
2084 bool NeedsCleanup = false;
2085 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002086 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
2087 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002088 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002089 LValue SharedsBase;
2090 if (!FirstprivateVars.empty()) {
2091 SharedsBase = CGF.MakeNaturalAlignAddrLValue(
2092 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2093 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
2094 SharedsTy);
2095 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002096 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
2097 cast<CapturedStmt>(*D.getAssociatedStmt()));
2098 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002099 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002100 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002101 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002102 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002103 if (auto *Elem = Pair.second.PrivateElemInit) {
2104 auto *OriginalVD = Pair.second.Original;
2105 auto *SharedField = CapturesInfo.lookup(OriginalVD);
2106 auto SharedRefLValue =
2107 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002108 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002109 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002110 // Initialize firstprivate array.
2111 if (!isa<CXXConstructExpr>(Init) ||
2112 CGF.isTrivialInitializer(Init)) {
2113 // Perform simple memcpy.
2114 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002115 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00002116 } else {
2117 // Initialize firstprivate array using element-by-element
2118 // intialization.
2119 CGF.EmitOMPAggregateAssign(
2120 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002121 Type, [&CGF, Elem, Init, &CapturesInfo](
2122 llvm::Value *DestElement, llvm::Value *SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00002123 // Clean up any temporaries needed by the initialization.
2124 CodeGenFunction::OMPPrivateScope InitScope(CGF);
2125 InitScope.addPrivate(Elem, [SrcElement]() -> llvm::Value *{
2126 return SrcElement;
2127 });
2128 (void)InitScope.Privatize();
2129 // Emit initialization for single element.
2130 auto *OldCapturedStmtInfo = CGF.CapturedStmtInfo;
2131 CGF.CapturedStmtInfo = &CapturesInfo;
2132 CGF.EmitAnyExprToMem(Init, DestElement,
2133 Init->getType().getQualifiers(),
2134 /*IsInitializer=*/false);
2135 CGF.CapturedStmtInfo = OldCapturedStmtInfo;
2136 });
2137 }
2138 } else {
2139 CodeGenFunction::OMPPrivateScope InitScope(CGF);
2140 InitScope.addPrivate(Elem, [SharedRefLValue]() -> llvm::Value *{
2141 return SharedRefLValue.getAddress();
2142 });
2143 (void)InitScope.Privatize();
2144 auto *OldCapturedStmtInfo = CGF.CapturedStmtInfo;
2145 CGF.CapturedStmtInfo = &CapturesInfo;
2146 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
2147 /*capturedByInit=*/false);
2148 CGF.CapturedStmtInfo = OldCapturedStmtInfo;
2149 }
2150 } else {
2151 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
2152 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002153 }
2154 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002155 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002156 }
2157 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002158 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00002159 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00002160 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
2161 KmpTaskTWithPrivatesPtrQTy,
2162 KmpTaskTWithPrivatesQTy)
2163 : llvm::ConstantPointerNull::get(
2164 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
2165 LValue Destructor = CGF.EmitLValueForField(
2166 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
2167 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2168 DestructorFn, KmpRoutineEntryPtrTy),
2169 Destructor);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002170 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
2171 // libcall.
2172 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
2173 // *new_task);
Alexey Bataev1d677132015-04-22 13:57:31 +00002174 auto *ThreadID = getThreadID(CGF, Loc);
2175 llvm::Value *TaskArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID, NewTask};
2176 auto &&ThenCodeGen = [this, &TaskArgs](CodeGenFunction &CGF) {
2177 // TODO: add check for untied tasks.
2178 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
2179 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002180 typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
2181 IfCallEndCleanup;
Alexey Bataev1d677132015-04-22 13:57:31 +00002182 auto &&ElseCodeGen =
2183 [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry](
2184 CodeGenFunction &CGF) {
2185 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
2186 CGF.EmitRuntimeCall(
2187 createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs);
2188 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
2189 // kmp_task_t *new_task);
Alexey Bataeva744ff52015-05-05 09:24:37 +00002190 CGF.EHStack.pushCleanup<IfCallEndCleanup>(
Alexey Bataev1d677132015-04-22 13:57:31 +00002191 NormalAndEHCleanup,
2192 createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
2193 llvm::makeArrayRef(TaskArgs));
2194
2195 // Call proxy_task_entry(gtid, new_task);
2196 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
2197 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
2198 };
2199 if (IfCond) {
2200 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
2201 } else {
2202 CodeGenFunction::RunCleanupsScope Scope(CGF);
2203 ThenCodeGen(CGF);
2204 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00002205}
2206
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002207static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
2208 llvm::Type *ArgsType,
2209 ArrayRef<const Expr *> LHSExprs,
2210 ArrayRef<const Expr *> RHSExprs,
2211 ArrayRef<const Expr *> ReductionOps) {
2212 auto &C = CGM.getContext();
2213
2214 // void reduction_func(void *LHSArg, void *RHSArg);
2215 FunctionArgList Args;
2216 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2217 C.VoidPtrTy);
2218 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2219 C.VoidPtrTy);
2220 Args.push_back(&LHSArg);
2221 Args.push_back(&RHSArg);
2222 FunctionType::ExtInfo EI;
2223 auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2224 C.VoidTy, Args, EI, /*isVariadic=*/false);
2225 auto *Fn = llvm::Function::Create(
2226 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2227 ".omp.reduction.reduction_func", &CGM.getModule());
2228 CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
2229 CodeGenFunction CGF(CGM);
2230 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2231
2232 // Dst = (void*[n])(LHSArg);
2233 // Src = (void*[n])(RHSArg);
2234 auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2235 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
2236 CGF.PointerAlignInBytes),
2237 ArgsType);
2238 auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2239 CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
2240 CGF.PointerAlignInBytes),
2241 ArgsType);
2242
2243 // ...
2244 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
2245 // ...
2246 CodeGenFunction::OMPPrivateScope Scope(CGF);
2247 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
2248 Scope.addPrivate(
2249 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()),
2250 [&]() -> llvm::Value *{
2251 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2252 CGF.Builder.CreateAlignedLoad(
2253 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, RHS, I),
2254 CGM.PointerAlignInBytes),
2255 CGF.ConvertTypeForMem(C.getPointerType(RHSExprs[I]->getType())));
2256 });
2257 Scope.addPrivate(
2258 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()),
2259 [&]() -> llvm::Value *{
2260 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2261 CGF.Builder.CreateAlignedLoad(
2262 CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, LHS, I),
2263 CGM.PointerAlignInBytes),
2264 CGF.ConvertTypeForMem(C.getPointerType(LHSExprs[I]->getType())));
2265 });
2266 }
2267 Scope.Privatize();
2268 for (auto *E : ReductionOps) {
2269 CGF.EmitIgnoredExpr(E);
2270 }
2271 Scope.ForceCleanup();
2272 CGF.FinishFunction();
2273 return Fn;
2274}
2275
2276void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
2277 ArrayRef<const Expr *> LHSExprs,
2278 ArrayRef<const Expr *> RHSExprs,
2279 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002280 bool WithNowait, bool SimpleReduction) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002281 // Next code should be emitted for reduction:
2282 //
2283 // static kmp_critical_name lock = { 0 };
2284 //
2285 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
2286 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
2287 // ...
2288 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
2289 // *(Type<n>-1*)rhs[<n>-1]);
2290 // }
2291 //
2292 // ...
2293 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
2294 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2295 // RedList, reduce_func, &<lock>)) {
2296 // case 1:
2297 // ...
2298 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2299 // ...
2300 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2301 // break;
2302 // case 2:
2303 // ...
2304 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2305 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00002306 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002307 // break;
2308 // default:;
2309 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002310 //
2311 // if SimpleReduction is true, only the next code is generated:
2312 // ...
2313 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2314 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002315
2316 auto &C = CGM.getContext();
2317
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00002318 if (SimpleReduction) {
2319 CodeGenFunction::RunCleanupsScope Scope(CGF);
2320 for (auto *E : ReductionOps) {
2321 CGF.EmitIgnoredExpr(E);
2322 }
2323 return;
2324 }
2325
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002326 // 1. Build a list of reduction variables.
2327 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2328 llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
2329 QualType ReductionArrayTy =
2330 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2331 /*IndexTypeQuals=*/0);
2332 auto *ReductionList =
2333 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2334 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
2335 auto *Elem = CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, ReductionList, I);
2336 CGF.Builder.CreateAlignedStore(
2337 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2338 CGF.EmitLValue(RHSExprs[I]).getAddress(), CGF.VoidPtrTy),
2339 Elem, CGM.PointerAlignInBytes);
2340 }
2341
2342 // 2. Emit reduce_func().
2343 auto *ReductionFn = emitReductionFunction(
2344 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
2345 RHSExprs, ReductionOps);
2346
2347 // 3. Create static kmp_critical_name lock = { 0 };
2348 auto *Lock = getCriticalRegionLock(".reduction");
2349
2350 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2351 // RedList, reduce_func, &<lock>);
2352 auto *IdentTLoc = emitUpdateLocation(
2353 CGF, Loc,
2354 static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
2355 auto *ThreadId = getThreadID(CGF, Loc);
2356 auto *ReductionArrayTySize = llvm::ConstantInt::get(
2357 CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
2358 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList,
2359 CGF.VoidPtrTy);
2360 llvm::Value *Args[] = {
2361 IdentTLoc, // ident_t *<loc>
2362 ThreadId, // i32 <gtid>
2363 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
2364 ReductionArrayTySize, // size_type sizeof(RedList)
2365 RL, // void *RedList
2366 ReductionFn, // void (*) (void *, void *) <reduce_func>
2367 Lock // kmp_critical_name *&<lock>
2368 };
2369 auto Res = CGF.EmitRuntimeCall(
2370 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
2371 : OMPRTL__kmpc_reduce),
2372 Args);
2373
2374 // 5. Build switch(res)
2375 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2376 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
2377
2378 // 6. Build case 1:
2379 // ...
2380 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2381 // ...
2382 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2383 // break;
2384 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2385 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2386 CGF.EmitBlock(Case1BB);
2387
2388 {
2389 CodeGenFunction::RunCleanupsScope Scope(CGF);
2390 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2391 llvm::Value *EndArgs[] = {
2392 IdentTLoc, // ident_t *<loc>
2393 ThreadId, // i32 <gtid>
2394 Lock // kmp_critical_name *&<lock>
2395 };
Alexey Bataeva744ff52015-05-05 09:24:37 +00002396 CGF.EHStack
2397 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2398 NormalAndEHCleanup,
2399 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
2400 : OMPRTL__kmpc_end_reduce),
2401 llvm::makeArrayRef(EndArgs));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002402 for (auto *E : ReductionOps) {
2403 CGF.EmitIgnoredExpr(E);
2404 }
2405 }
2406
2407 CGF.EmitBranch(DefaultBB);
2408
2409 // 7. Build case 2:
2410 // ...
2411 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2412 // ...
2413 // break;
2414 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
2415 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
2416 CGF.EmitBlock(Case2BB);
2417
2418 {
2419 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataev69a47792015-05-07 03:54:03 +00002420 if (!WithNowait) {
2421 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
2422 llvm::Value *EndArgs[] = {
2423 IdentTLoc, // ident_t *<loc>
2424 ThreadId, // i32 <gtid>
2425 Lock // kmp_critical_name *&<lock>
2426 };
2427 CGF.EHStack
2428 .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
2429 NormalAndEHCleanup,
2430 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
2431 llvm::makeArrayRef(EndArgs));
2432 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002433 auto I = LHSExprs.begin();
2434 for (auto *E : ReductionOps) {
2435 const Expr *XExpr = nullptr;
2436 const Expr *EExpr = nullptr;
2437 const Expr *UpExpr = nullptr;
2438 BinaryOperatorKind BO = BO_Comma;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002439 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2440 if (BO->getOpcode() == BO_Assign) {
2441 XExpr = BO->getLHS();
2442 UpExpr = BO->getRHS();
2443 }
2444 }
Alexey Bataev69a47792015-05-07 03:54:03 +00002445 // Try to emit update expression as a simple atomic.
2446 auto *RHSExpr = UpExpr;
2447 if (RHSExpr) {
2448 // Analyze RHS part of the whole expression.
2449 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
2450 RHSExpr->IgnoreParenImpCasts())) {
2451 // If this is a conditional operator, analyze its condition for
2452 // min/max reduction operator.
2453 RHSExpr = ACO->getCond();
2454 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002455 if (auto *BORHS =
Alexey Bataev69a47792015-05-07 03:54:03 +00002456 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00002457 EExpr = BORHS->getRHS();
2458 BO = BORHS->getOpcode();
2459 }
2460 }
2461 if (XExpr) {
2462 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2463 LValue X = CGF.EmitLValue(XExpr);
2464 RValue E;
2465 if (EExpr)
2466 E = CGF.EmitAnyExpr(EExpr);
2467 CGF.EmitOMPAtomicSimpleUpdateExpr(
2468 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
2469 [&CGF, UpExpr, VD](RValue XRValue) {
2470 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
2471 PrivateScope.addPrivate(
2472 VD, [&CGF, VD, XRValue]() -> llvm::Value *{
2473 auto *LHSTemp = CGF.CreateMemTemp(VD->getType());
2474 CGF.EmitStoreThroughLValue(
2475 XRValue,
2476 CGF.MakeNaturalAlignAddrLValue(LHSTemp, VD->getType()));
2477 return LHSTemp;
2478 });
2479 (void)PrivateScope.Privatize();
2480 return CGF.EmitAnyExpr(UpExpr);
2481 });
2482 } else {
2483 // Emit as a critical region.
2484 emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
2485 CGF.EmitIgnoredExpr(E);
2486 }, Loc);
2487 }
2488 ++I;
2489 }
2490 }
2491
2492 CGF.EmitBranch(DefaultBB);
2493 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2494}
2495
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002496void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
2497 SourceLocation Loc) {
2498 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
2499 // global_tid);
2500 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2501 // Ignore return result until untied tasks are supported.
2502 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
2503}
2504
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002505void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
2506 const RegionCodeGenTy &CodeGen) {
2507 InlinedOpenMPRegionRAII Region(CGF, CodeGen);
2508 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002509}
2510