File: | build/source/clang/lib/CodeGen/CGOpenMPRuntime.cpp |
Warning: | line 2197, column 3 Address of stack memory associated with local variable 'Action' is still referred to by a temporary object on the stack upon returning to the caller. This will be a dangling reference |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This provides a class for OpenMP runtime code generation. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "CGOpenMPRuntime.h" | |||
14 | #include "CGCXXABI.h" | |||
15 | #include "CGCleanup.h" | |||
16 | #include "CGRecordLayout.h" | |||
17 | #include "CodeGenFunction.h" | |||
18 | #include "TargetInfo.h" | |||
19 | #include "clang/AST/APValue.h" | |||
20 | #include "clang/AST/Attr.h" | |||
21 | #include "clang/AST/Decl.h" | |||
22 | #include "clang/AST/OpenMPClause.h" | |||
23 | #include "clang/AST/StmtOpenMP.h" | |||
24 | #include "clang/AST/StmtVisitor.h" | |||
25 | #include "clang/Basic/BitmaskEnum.h" | |||
26 | #include "clang/Basic/FileManager.h" | |||
27 | #include "clang/Basic/OpenMPKinds.h" | |||
28 | #include "clang/Basic/SourceManager.h" | |||
29 | #include "clang/CodeGen/ConstantInitBuilder.h" | |||
30 | #include "llvm/ADT/ArrayRef.h" | |||
31 | #include "llvm/ADT/SetOperations.h" | |||
32 | #include "llvm/ADT/SmallBitVector.h" | |||
33 | #include "llvm/ADT/StringExtras.h" | |||
34 | #include "llvm/Bitcode/BitcodeReader.h" | |||
35 | #include "llvm/IR/Constants.h" | |||
36 | #include "llvm/IR/DerivedTypes.h" | |||
37 | #include "llvm/IR/GlobalValue.h" | |||
38 | #include "llvm/IR/InstrTypes.h" | |||
39 | #include "llvm/IR/Value.h" | |||
40 | #include "llvm/Support/AtomicOrdering.h" | |||
41 | #include "llvm/Support/Format.h" | |||
42 | #include "llvm/Support/raw_ostream.h" | |||
43 | #include <cassert> | |||
44 | #include <numeric> | |||
45 | #include <optional> | |||
46 | ||||
47 | using namespace clang; | |||
48 | using namespace CodeGen; | |||
49 | using namespace llvm::omp; | |||
50 | ||||
51 | namespace { | |||
52 | /// Base class for handling code generation inside OpenMP regions. | |||
53 | class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo { | |||
54 | public: | |||
55 | /// Kinds of OpenMP regions used in codegen. | |||
56 | enum CGOpenMPRegionKind { | |||
57 | /// Region with outlined function for standalone 'parallel' | |||
58 | /// directive. | |||
59 | ParallelOutlinedRegion, | |||
60 | /// Region with outlined function for standalone 'task' directive. | |||
61 | TaskOutlinedRegion, | |||
62 | /// Region for constructs that do not require function outlining, | |||
63 | /// like 'for', 'sections', 'atomic' etc. directives. | |||
64 | InlinedRegion, | |||
65 | /// Region with outlined function for standalone 'target' directive. | |||
66 | TargetRegion, | |||
67 | }; | |||
68 | ||||
69 | CGOpenMPRegionInfo(const CapturedStmt &CS, | |||
70 | const CGOpenMPRegionKind RegionKind, | |||
71 | const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind, | |||
72 | bool HasCancel) | |||
73 | : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind), | |||
74 | CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {} | |||
75 | ||||
76 | CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind, | |||
77 | const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind, | |||
78 | bool HasCancel) | |||
79 | : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen), | |||
80 | Kind(Kind), HasCancel(HasCancel) {} | |||
81 | ||||
82 | /// Get a variable or parameter for storing global thread id | |||
83 | /// inside OpenMP construct. | |||
84 | virtual const VarDecl *getThreadIDVariable() const = 0; | |||
85 | ||||
86 | /// Emit the captured statement body. | |||
87 | void EmitBody(CodeGenFunction &CGF, const Stmt *S) override; | |||
88 | ||||
89 | /// Get an LValue for the current ThreadID variable. | |||
90 | /// \return LValue for thread id variable. This LValue always has type int32*. | |||
91 | virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF); | |||
92 | ||||
93 | virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {} | |||
94 | ||||
95 | CGOpenMPRegionKind getRegionKind() const { return RegionKind; } | |||
96 | ||||
97 | OpenMPDirectiveKind getDirectiveKind() const { return Kind; } | |||
98 | ||||
99 | bool hasCancel() const { return HasCancel; } | |||
100 | ||||
101 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
102 | return Info->getKind() == CR_OpenMP; | |||
103 | } | |||
104 | ||||
105 | ~CGOpenMPRegionInfo() override = default; | |||
106 | ||||
107 | protected: | |||
108 | CGOpenMPRegionKind RegionKind; | |||
109 | RegionCodeGenTy CodeGen; | |||
110 | OpenMPDirectiveKind Kind; | |||
111 | bool HasCancel; | |||
112 | }; | |||
113 | ||||
114 | /// API for captured statement code generation in OpenMP constructs. | |||
115 | class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo { | |||
116 | public: | |||
117 | CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar, | |||
118 | const RegionCodeGenTy &CodeGen, | |||
119 | OpenMPDirectiveKind Kind, bool HasCancel, | |||
120 | StringRef HelperName) | |||
121 | : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind, | |||
122 | HasCancel), | |||
123 | ThreadIDVar(ThreadIDVar), HelperName(HelperName) { | |||
124 | assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.")(static_cast <bool> (ThreadIDVar != nullptr && "No ThreadID in OpenMP region." ) ? void (0) : __assert_fail ("ThreadIDVar != nullptr && \"No ThreadID in OpenMP region.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 124, __extension__ __PRETTY_FUNCTION__)); | |||
125 | } | |||
126 | ||||
127 | /// Get a variable or parameter for storing global thread id | |||
128 | /// inside OpenMP construct. | |||
129 | const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; } | |||
130 | ||||
131 | /// Get the name of the capture helper. | |||
132 | StringRef getHelperName() const override { return HelperName; } | |||
133 | ||||
134 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
135 | return CGOpenMPRegionInfo::classof(Info) && | |||
136 | cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == | |||
137 | ParallelOutlinedRegion; | |||
138 | } | |||
139 | ||||
140 | private: | |||
141 | /// A variable or parameter storing global thread id for OpenMP | |||
142 | /// constructs. | |||
143 | const VarDecl *ThreadIDVar; | |||
144 | StringRef HelperName; | |||
145 | }; | |||
146 | ||||
147 | /// API for captured statement code generation in OpenMP constructs. | |||
148 | class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo { | |||
149 | public: | |||
150 | class UntiedTaskActionTy final : public PrePostActionTy { | |||
151 | bool Untied; | |||
152 | const VarDecl *PartIDVar; | |||
153 | const RegionCodeGenTy UntiedCodeGen; | |||
154 | llvm::SwitchInst *UntiedSwitch = nullptr; | |||
155 | ||||
156 | public: | |||
157 | UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar, | |||
158 | const RegionCodeGenTy &UntiedCodeGen) | |||
159 | : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {} | |||
160 | void Enter(CodeGenFunction &CGF) override { | |||
161 | if (Untied) { | |||
162 | // Emit task switching point. | |||
163 | LValue PartIdLVal = CGF.EmitLoadOfPointerLValue( | |||
164 | CGF.GetAddrOfLocalVar(PartIDVar), | |||
165 | PartIDVar->getType()->castAs<PointerType>()); | |||
166 | llvm::Value *Res = | |||
167 | CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation()); | |||
168 | llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done."); | |||
169 | UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB); | |||
170 | CGF.EmitBlock(DoneBB); | |||
171 | CGF.EmitBranchThroughCleanup(CGF.ReturnBlock); | |||
172 | CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp.")); | |||
173 | UntiedSwitch->addCase(CGF.Builder.getInt32(0), | |||
174 | CGF.Builder.GetInsertBlock()); | |||
175 | emitUntiedSwitch(CGF); | |||
176 | } | |||
177 | } | |||
178 | void emitUntiedSwitch(CodeGenFunction &CGF) const { | |||
179 | if (Untied) { | |||
180 | LValue PartIdLVal = CGF.EmitLoadOfPointerLValue( | |||
181 | CGF.GetAddrOfLocalVar(PartIDVar), | |||
182 | PartIDVar->getType()->castAs<PointerType>()); | |||
183 | CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()), | |||
184 | PartIdLVal); | |||
185 | UntiedCodeGen(CGF); | |||
186 | CodeGenFunction::JumpDest CurPoint = | |||
187 | CGF.getJumpDestInCurrentScope(".untied.next."); | |||
188 | CGF.EmitBranch(CGF.ReturnBlock.getBlock()); | |||
189 | CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp.")); | |||
190 | UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()), | |||
191 | CGF.Builder.GetInsertBlock()); | |||
192 | CGF.EmitBranchThroughCleanup(CurPoint); | |||
193 | CGF.EmitBlock(CurPoint.getBlock()); | |||
194 | } | |||
195 | } | |||
196 | unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); } | |||
197 | }; | |||
198 | CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS, | |||
199 | const VarDecl *ThreadIDVar, | |||
200 | const RegionCodeGenTy &CodeGen, | |||
201 | OpenMPDirectiveKind Kind, bool HasCancel, | |||
202 | const UntiedTaskActionTy &Action) | |||
203 | : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel), | |||
204 | ThreadIDVar(ThreadIDVar), Action(Action) { | |||
205 | assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.")(static_cast <bool> (ThreadIDVar != nullptr && "No ThreadID in OpenMP region." ) ? void (0) : __assert_fail ("ThreadIDVar != nullptr && \"No ThreadID in OpenMP region.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 205, __extension__ __PRETTY_FUNCTION__)); | |||
206 | } | |||
207 | ||||
208 | /// Get a variable or parameter for storing global thread id | |||
209 | /// inside OpenMP construct. | |||
210 | const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; } | |||
211 | ||||
212 | /// Get an LValue for the current ThreadID variable. | |||
213 | LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override; | |||
214 | ||||
215 | /// Get the name of the capture helper. | |||
216 | StringRef getHelperName() const override { return ".omp_outlined."; } | |||
217 | ||||
218 | void emitUntiedSwitch(CodeGenFunction &CGF) override { | |||
219 | Action.emitUntiedSwitch(CGF); | |||
220 | } | |||
221 | ||||
222 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
223 | return CGOpenMPRegionInfo::classof(Info) && | |||
224 | cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == | |||
225 | TaskOutlinedRegion; | |||
226 | } | |||
227 | ||||
228 | private: | |||
229 | /// A variable or parameter storing global thread id for OpenMP | |||
230 | /// constructs. | |||
231 | const VarDecl *ThreadIDVar; | |||
232 | /// Action for emitting code for untied tasks. | |||
233 | const UntiedTaskActionTy &Action; | |||
234 | }; | |||
235 | ||||
236 | /// API for inlined captured statement code generation in OpenMP | |||
237 | /// constructs. | |||
238 | class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo { | |||
239 | public: | |||
240 | CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI, | |||
241 | const RegionCodeGenTy &CodeGen, | |||
242 | OpenMPDirectiveKind Kind, bool HasCancel) | |||
243 | : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel), | |||
244 | OldCSI(OldCSI), | |||
245 | OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {} | |||
246 | ||||
247 | // Retrieve the value of the context parameter. | |||
248 | llvm::Value *getContextValue() const override { | |||
249 | if (OuterRegionInfo) | |||
250 | return OuterRegionInfo->getContextValue(); | |||
251 | llvm_unreachable("No context value for inlined OpenMP region")::llvm::llvm_unreachable_internal("No context value for inlined OpenMP region" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 251); | |||
252 | } | |||
253 | ||||
254 | void setContextValue(llvm::Value *V) override { | |||
255 | if (OuterRegionInfo) { | |||
256 | OuterRegionInfo->setContextValue(V); | |||
257 | return; | |||
258 | } | |||
259 | llvm_unreachable("No context value for inlined OpenMP region")::llvm::llvm_unreachable_internal("No context value for inlined OpenMP region" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 259); | |||
260 | } | |||
261 | ||||
262 | /// Lookup the captured field decl for a variable. | |||
263 | const FieldDecl *lookup(const VarDecl *VD) const override { | |||
264 | if (OuterRegionInfo) | |||
265 | return OuterRegionInfo->lookup(VD); | |||
266 | // If there is no outer outlined region,no need to lookup in a list of | |||
267 | // captured variables, we can use the original one. | |||
268 | return nullptr; | |||
269 | } | |||
270 | ||||
271 | FieldDecl *getThisFieldDecl() const override { | |||
272 | if (OuterRegionInfo) | |||
273 | return OuterRegionInfo->getThisFieldDecl(); | |||
274 | return nullptr; | |||
275 | } | |||
276 | ||||
277 | /// Get a variable or parameter for storing global thread id | |||
278 | /// inside OpenMP construct. | |||
279 | const VarDecl *getThreadIDVariable() const override { | |||
280 | if (OuterRegionInfo) | |||
281 | return OuterRegionInfo->getThreadIDVariable(); | |||
282 | return nullptr; | |||
283 | } | |||
284 | ||||
285 | /// Get an LValue for the current ThreadID variable. | |||
286 | LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override { | |||
287 | if (OuterRegionInfo) | |||
288 | return OuterRegionInfo->getThreadIDVariableLValue(CGF); | |||
289 | llvm_unreachable("No LValue for inlined OpenMP construct")::llvm::llvm_unreachable_internal("No LValue for inlined OpenMP construct" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 289); | |||
290 | } | |||
291 | ||||
292 | /// Get the name of the capture helper. | |||
293 | StringRef getHelperName() const override { | |||
294 | if (auto *OuterRegionInfo = getOldCSI()) | |||
295 | return OuterRegionInfo->getHelperName(); | |||
296 | llvm_unreachable("No helper name for inlined OpenMP construct")::llvm::llvm_unreachable_internal("No helper name for inlined OpenMP construct" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 296); | |||
297 | } | |||
298 | ||||
299 | void emitUntiedSwitch(CodeGenFunction &CGF) override { | |||
300 | if (OuterRegionInfo) | |||
301 | OuterRegionInfo->emitUntiedSwitch(CGF); | |||
302 | } | |||
303 | ||||
304 | CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; } | |||
305 | ||||
306 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
307 | return CGOpenMPRegionInfo::classof(Info) && | |||
308 | cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion; | |||
309 | } | |||
310 | ||||
311 | ~CGOpenMPInlinedRegionInfo() override = default; | |||
312 | ||||
313 | private: | |||
314 | /// CodeGen info about outer OpenMP region. | |||
315 | CodeGenFunction::CGCapturedStmtInfo *OldCSI; | |||
316 | CGOpenMPRegionInfo *OuterRegionInfo; | |||
317 | }; | |||
318 | ||||
319 | /// API for captured statement code generation in OpenMP target | |||
320 | /// constructs. For this captures, implicit parameters are used instead of the | |||
321 | /// captured fields. The name of the target region has to be unique in a given | |||
322 | /// application so it is provided by the client, because only the client has | |||
323 | /// the information to generate that. | |||
324 | class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo { | |||
325 | public: | |||
326 | CGOpenMPTargetRegionInfo(const CapturedStmt &CS, | |||
327 | const RegionCodeGenTy &CodeGen, StringRef HelperName) | |||
328 | : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target, | |||
329 | /*HasCancel=*/false), | |||
330 | HelperName(HelperName) {} | |||
331 | ||||
332 | /// This is unused for target regions because each starts executing | |||
333 | /// with a single thread. | |||
334 | const VarDecl *getThreadIDVariable() const override { return nullptr; } | |||
335 | ||||
336 | /// Get the name of the capture helper. | |||
337 | StringRef getHelperName() const override { return HelperName; } | |||
338 | ||||
339 | static bool classof(const CGCapturedStmtInfo *Info) { | |||
340 | return CGOpenMPRegionInfo::classof(Info) && | |||
341 | cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion; | |||
342 | } | |||
343 | ||||
344 | private: | |||
345 | StringRef HelperName; | |||
346 | }; | |||
347 | ||||
348 | static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) { | |||
349 | llvm_unreachable("No codegen for expressions")::llvm::llvm_unreachable_internal("No codegen for expressions" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 349); | |||
350 | } | |||
351 | /// API for generation of expressions captured in a innermost OpenMP | |||
352 | /// region. | |||
353 | class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo { | |||
354 | public: | |||
355 | CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS) | |||
356 | : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen, | |||
357 | OMPD_unknown, | |||
358 | /*HasCancel=*/false), | |||
359 | PrivScope(CGF) { | |||
360 | // Make sure the globals captured in the provided statement are local by | |||
361 | // using the privatization logic. We assume the same variable is not | |||
362 | // captured more than once. | |||
363 | for (const auto &C : CS.captures()) { | |||
364 | if (!C.capturesVariable() && !C.capturesVariableByCopy()) | |||
365 | continue; | |||
366 | ||||
367 | const VarDecl *VD = C.getCapturedVar(); | |||
368 | if (VD->isLocalVarDeclOrParm()) | |||
369 | continue; | |||
370 | ||||
371 | DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD), | |||
372 | /*RefersToEnclosingVariableOrCapture=*/false, | |||
373 | VD->getType().getNonReferenceType(), VK_LValue, | |||
374 | C.getLocation()); | |||
375 | PrivScope.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress(CGF)); | |||
376 | } | |||
377 | (void)PrivScope.Privatize(); | |||
378 | } | |||
379 | ||||
380 | /// Lookup the captured field decl for a variable. | |||
381 | const FieldDecl *lookup(const VarDecl *VD) const override { | |||
382 | if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD)) | |||
383 | return FD; | |||
384 | return nullptr; | |||
385 | } | |||
386 | ||||
387 | /// Emit the captured statement body. | |||
388 | void EmitBody(CodeGenFunction &CGF, const Stmt *S) override { | |||
389 | llvm_unreachable("No body for expressions")::llvm::llvm_unreachable_internal("No body for expressions", "clang/lib/CodeGen/CGOpenMPRuntime.cpp" , 389); | |||
390 | } | |||
391 | ||||
392 | /// Get a variable or parameter for storing global thread id | |||
393 | /// inside OpenMP construct. | |||
394 | const VarDecl *getThreadIDVariable() const override { | |||
395 | llvm_unreachable("No thread id for expressions")::llvm::llvm_unreachable_internal("No thread id for expressions" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 395); | |||
396 | } | |||
397 | ||||
398 | /// Get the name of the capture helper. | |||
399 | StringRef getHelperName() const override { | |||
400 | llvm_unreachable("No helper name for expressions")::llvm::llvm_unreachable_internal("No helper name for expressions" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 400); | |||
401 | } | |||
402 | ||||
403 | static bool classof(const CGCapturedStmtInfo *Info) { return false; } | |||
404 | ||||
405 | private: | |||
406 | /// Private scope to capture global variables. | |||
407 | CodeGenFunction::OMPPrivateScope PrivScope; | |||
408 | }; | |||
409 | ||||
410 | /// RAII for emitting code of OpenMP constructs. | |||
411 | class InlinedOpenMPRegionRAII { | |||
412 | CodeGenFunction &CGF; | |||
413 | llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields; | |||
414 | FieldDecl *LambdaThisCaptureField = nullptr; | |||
415 | const CodeGen::CGBlockInfo *BlockInfo = nullptr; | |||
416 | bool NoInheritance = false; | |||
417 | ||||
418 | public: | |||
419 | /// Constructs region for combined constructs. | |||
420 | /// \param CodeGen Code generation sequence for combined directives. Includes | |||
421 | /// a list of functions used for code generation of implicitly inlined | |||
422 | /// regions. | |||
423 | InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen, | |||
424 | OpenMPDirectiveKind Kind, bool HasCancel, | |||
425 | bool NoInheritance = true) | |||
426 | : CGF(CGF), NoInheritance(NoInheritance) { | |||
427 | // Start emission for the construct. | |||
428 | CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo( | |||
429 | CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel); | |||
430 | if (NoInheritance) { | |||
431 | std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields); | |||
432 | LambdaThisCaptureField = CGF.LambdaThisCaptureField; | |||
433 | CGF.LambdaThisCaptureField = nullptr; | |||
434 | BlockInfo = CGF.BlockInfo; | |||
435 | CGF.BlockInfo = nullptr; | |||
436 | } | |||
437 | } | |||
438 | ||||
439 | ~InlinedOpenMPRegionRAII() { | |||
440 | // Restore original CapturedStmtInfo only if we're done with code emission. | |||
441 | auto *OldCSI = | |||
442 | cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI(); | |||
443 | delete CGF.CapturedStmtInfo; | |||
444 | CGF.CapturedStmtInfo = OldCSI; | |||
445 | if (NoInheritance) { | |||
446 | std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields); | |||
447 | CGF.LambdaThisCaptureField = LambdaThisCaptureField; | |||
448 | CGF.BlockInfo = BlockInfo; | |||
449 | } | |||
450 | } | |||
451 | }; | |||
452 | ||||
453 | /// Values for bit flags used in the ident_t to describe the fields. | |||
454 | /// All enumeric elements are named and described in accordance with the code | |||
455 | /// from https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h | |||
456 | enum OpenMPLocationFlags : unsigned { | |||
457 | /// Use trampoline for internal microtask. | |||
458 | OMP_IDENT_IMD = 0x01, | |||
459 | /// Use c-style ident structure. | |||
460 | OMP_IDENT_KMPC = 0x02, | |||
461 | /// Atomic reduction option for kmpc_reduce. | |||
462 | OMP_ATOMIC_REDUCE = 0x10, | |||
463 | /// Explicit 'barrier' directive. | |||
464 | OMP_IDENT_BARRIER_EXPL = 0x20, | |||
465 | /// Implicit barrier in code. | |||
466 | OMP_IDENT_BARRIER_IMPL = 0x40, | |||
467 | /// Implicit barrier in 'for' directive. | |||
468 | OMP_IDENT_BARRIER_IMPL_FOR = 0x40, | |||
469 | /// Implicit barrier in 'sections' directive. | |||
470 | OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0, | |||
471 | /// Implicit barrier in 'single' directive. | |||
472 | OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140, | |||
473 | /// Call of __kmp_for_static_init for static loop. | |||
474 | OMP_IDENT_WORK_LOOP = 0x200, | |||
475 | /// Call of __kmp_for_static_init for sections. | |||
476 | OMP_IDENT_WORK_SECTIONS = 0x400, | |||
477 | /// Call of __kmp_for_static_init for distribute. | |||
478 | OMP_IDENT_WORK_DISTRIBUTE = 0x800, | |||
479 | LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)LLVM_BITMASK_LARGEST_ENUMERATOR = OMP_IDENT_WORK_DISTRIBUTE | |||
480 | }; | |||
481 | ||||
482 | namespace { | |||
483 | LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE()using ::llvm::BitmaskEnumDetail::operator~; using ::llvm::BitmaskEnumDetail ::operator|; using ::llvm::BitmaskEnumDetail::operator&; using ::llvm::BitmaskEnumDetail::operator^; using ::llvm::BitmaskEnumDetail ::operator|=; using ::llvm::BitmaskEnumDetail::operator&= ; using ::llvm::BitmaskEnumDetail::operator^=; | |||
484 | /// Values for bit flags for marking which requires clauses have been used. | |||
485 | enum OpenMPOffloadingRequiresDirFlags : int64_t { | |||
486 | /// flag undefined. | |||
487 | OMP_REQ_UNDEFINED = 0x000, | |||
488 | /// no requires clause present. | |||
489 | OMP_REQ_NONE = 0x001, | |||
490 | /// reverse_offload clause. | |||
491 | OMP_REQ_REVERSE_OFFLOAD = 0x002, | |||
492 | /// unified_address clause. | |||
493 | OMP_REQ_UNIFIED_ADDRESS = 0x004, | |||
494 | /// unified_shared_memory clause. | |||
495 | OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008, | |||
496 | /// dynamic_allocators clause. | |||
497 | OMP_REQ_DYNAMIC_ALLOCATORS = 0x010, | |||
498 | LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_REQ_DYNAMIC_ALLOCATORS)LLVM_BITMASK_LARGEST_ENUMERATOR = OMP_REQ_DYNAMIC_ALLOCATORS | |||
499 | }; | |||
500 | ||||
501 | } // anonymous namespace | |||
502 | ||||
503 | /// Describes ident structure that describes a source location. | |||
504 | /// All descriptions are taken from | |||
505 | /// https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h | |||
506 | /// Original structure: | |||
507 | /// typedef struct ident { | |||
508 | /// kmp_int32 reserved_1; /**< might be used in Fortran; | |||
509 | /// see above */ | |||
510 | /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags; | |||
511 | /// KMP_IDENT_KMPC identifies this union | |||
512 | /// member */ | |||
513 | /// kmp_int32 reserved_2; /**< not really used in Fortran any more; | |||
514 | /// see above */ | |||
515 | ///#if USE_ITT_BUILD | |||
516 | /// /* but currently used for storing | |||
517 | /// region-specific ITT */ | |||
518 | /// /* contextual information. */ | |||
519 | ///#endif /* USE_ITT_BUILD */ | |||
520 | /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for | |||
521 | /// C++ */ | |||
522 | /// char const *psource; /**< String describing the source location. | |||
523 | /// The string is composed of semi-colon separated | |||
524 | // fields which describe the source file, | |||
525 | /// the function and a pair of line numbers that | |||
526 | /// delimit the construct. | |||
527 | /// */ | |||
528 | /// } ident_t; | |||
529 | enum IdentFieldIndex { | |||
530 | /// might be used in Fortran | |||
531 | IdentField_Reserved_1, | |||
532 | /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member. | |||
533 | IdentField_Flags, | |||
534 | /// Not really used in Fortran any more | |||
535 | IdentField_Reserved_2, | |||
536 | /// Source[4] in Fortran, do not use for C++ | |||
537 | IdentField_Reserved_3, | |||
538 | /// String describing the source location. The string is composed of | |||
539 | /// semi-colon separated fields which describe the source file, the function | |||
540 | /// and a pair of line numbers that delimit the construct. | |||
541 | IdentField_PSource | |||
542 | }; | |||
543 | ||||
544 | /// Schedule types for 'omp for' loops (these enumerators are taken from | |||
545 | /// the enum sched_type in kmp.h). | |||
546 | enum OpenMPSchedType { | |||
547 | /// Lower bound for default (unordered) versions. | |||
548 | OMP_sch_lower = 32, | |||
549 | OMP_sch_static_chunked = 33, | |||
550 | OMP_sch_static = 34, | |||
551 | OMP_sch_dynamic_chunked = 35, | |||
552 | OMP_sch_guided_chunked = 36, | |||
553 | OMP_sch_runtime = 37, | |||
554 | OMP_sch_auto = 38, | |||
555 | /// static with chunk adjustment (e.g., simd) | |||
556 | OMP_sch_static_balanced_chunked = 45, | |||
557 | /// Lower bound for 'ordered' versions. | |||
558 | OMP_ord_lower = 64, | |||
559 | OMP_ord_static_chunked = 65, | |||
560 | OMP_ord_static = 66, | |||
561 | OMP_ord_dynamic_chunked = 67, | |||
562 | OMP_ord_guided_chunked = 68, | |||
563 | OMP_ord_runtime = 69, | |||
564 | OMP_ord_auto = 70, | |||
565 | OMP_sch_default = OMP_sch_static, | |||
566 | /// dist_schedule types | |||
567 | OMP_dist_sch_static_chunked = 91, | |||
568 | OMP_dist_sch_static = 92, | |||
569 | /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers. | |||
570 | /// Set if the monotonic schedule modifier was present. | |||
571 | OMP_sch_modifier_monotonic = (1 << 29), | |||
572 | /// Set if the nonmonotonic schedule modifier was present. | |||
573 | OMP_sch_modifier_nonmonotonic = (1 << 30), | |||
574 | }; | |||
575 | ||||
576 | /// A basic class for pre|post-action for advanced codegen sequence for OpenMP | |||
577 | /// region. | |||
578 | class CleanupTy final : public EHScopeStack::Cleanup { | |||
579 | PrePostActionTy *Action; | |||
580 | ||||
581 | public: | |||
582 | explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {} | |||
583 | void Emit(CodeGenFunction &CGF, Flags /*flags*/) override { | |||
584 | if (!CGF.HaveInsertPoint()) | |||
585 | return; | |||
586 | Action->Exit(CGF); | |||
587 | } | |||
588 | }; | |||
589 | ||||
590 | } // anonymous namespace | |||
591 | ||||
592 | void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const { | |||
593 | CodeGenFunction::RunCleanupsScope Scope(CGF); | |||
594 | if (PrePostAction) { | |||
595 | CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction); | |||
596 | Callback(CodeGen, CGF, *PrePostAction); | |||
597 | } else { | |||
598 | PrePostActionTy Action; | |||
599 | Callback(CodeGen, CGF, Action); | |||
600 | } | |||
601 | } | |||
602 | ||||
603 | /// Check if the combiner is a call to UDR combiner and if it is so return the | |||
604 | /// UDR decl used for reduction. | |||
605 | static const OMPDeclareReductionDecl * | |||
606 | getReductionInit(const Expr *ReductionOp) { | |||
607 | if (const auto *CE = dyn_cast<CallExpr>(ReductionOp)) | |||
608 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee())) | |||
609 | if (const auto *DRE = | |||
610 | dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts())) | |||
611 | if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) | |||
612 | return DRD; | |||
613 | return nullptr; | |||
614 | } | |||
615 | ||||
616 | static void emitInitWithReductionInitializer(CodeGenFunction &CGF, | |||
617 | const OMPDeclareReductionDecl *DRD, | |||
618 | const Expr *InitOp, | |||
619 | Address Private, Address Original, | |||
620 | QualType Ty) { | |||
621 | if (DRD->getInitializer()) { | |||
622 | std::pair<llvm::Function *, llvm::Function *> Reduction = | |||
623 | CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD); | |||
624 | const auto *CE = cast<CallExpr>(InitOp); | |||
625 | const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee()); | |||
626 | const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); | |||
627 | const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); | |||
628 | const auto *LHSDRE = | |||
629 | cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr()); | |||
630 | const auto *RHSDRE = | |||
631 | cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr()); | |||
632 | CodeGenFunction::OMPPrivateScope PrivateScope(CGF); | |||
633 | PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()), Private); | |||
634 | PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()), Original); | |||
635 | (void)PrivateScope.Privatize(); | |||
636 | RValue Func = RValue::get(Reduction.second); | |||
637 | CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func); | |||
638 | CGF.EmitIgnoredExpr(InitOp); | |||
639 | } else { | |||
640 | llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty); | |||
641 | std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"}); | |||
642 | auto *GV = new llvm::GlobalVariable( | |||
643 | CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true, | |||
644 | llvm::GlobalValue::PrivateLinkage, Init, Name); | |||
645 | LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty); | |||
646 | RValue InitRVal; | |||
647 | switch (CGF.getEvaluationKind(Ty)) { | |||
648 | case TEK_Scalar: | |||
649 | InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation()); | |||
650 | break; | |||
651 | case TEK_Complex: | |||
652 | InitRVal = | |||
653 | RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation())); | |||
654 | break; | |||
655 | case TEK_Aggregate: { | |||
656 | OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_LValue); | |||
657 | CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, LV); | |||
658 | CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(), | |||
659 | /*IsInitializer=*/false); | |||
660 | return; | |||
661 | } | |||
662 | } | |||
663 | OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_PRValue); | |||
664 | CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal); | |||
665 | CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(), | |||
666 | /*IsInitializer=*/false); | |||
667 | } | |||
668 | } | |||
669 | ||||
670 | /// Emit initialization of arrays of complex types. | |||
671 | /// \param DestAddr Address of the array. | |||
672 | /// \param Type Type of array. | |||
673 | /// \param Init Initial expression of array. | |||
674 | /// \param SrcAddr Address of the original array. | |||
675 | static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr, | |||
676 | QualType Type, bool EmitDeclareReductionInit, | |||
677 | const Expr *Init, | |||
678 | const OMPDeclareReductionDecl *DRD, | |||
679 | Address SrcAddr = Address::invalid()) { | |||
680 | // Perform element-by-element initialization. | |||
681 | QualType ElementTy; | |||
682 | ||||
683 | // Drill down to the base element type on both arrays. | |||
684 | const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe(); | |||
685 | llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr); | |||
686 | if (DRD) | |||
687 | SrcAddr = | |||
688 | CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); | |||
689 | ||||
690 | llvm::Value *SrcBegin = nullptr; | |||
691 | if (DRD) | |||
692 | SrcBegin = SrcAddr.getPointer(); | |||
693 | llvm::Value *DestBegin = DestAddr.getPointer(); | |||
694 | // Cast from pointer to array type to pointer to single element. | |||
695 | llvm::Value *DestEnd = | |||
696 | CGF.Builder.CreateGEP(DestAddr.getElementType(), DestBegin, NumElements); | |||
697 | // The basic structure here is a while-do loop. | |||
698 | llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body"); | |||
699 | llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done"); | |||
700 | llvm::Value *IsEmpty = | |||
701 | CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty"); | |||
702 | CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); | |||
703 | ||||
704 | // Enter the loop body, making that address the current address. | |||
705 | llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); | |||
706 | CGF.EmitBlock(BodyBB); | |||
707 | ||||
708 | CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy); | |||
709 | ||||
710 | llvm::PHINode *SrcElementPHI = nullptr; | |||
711 | Address SrcElementCurrent = Address::invalid(); | |||
712 | if (DRD) { | |||
713 | SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2, | |||
714 | "omp.arraycpy.srcElementPast"); | |||
715 | SrcElementPHI->addIncoming(SrcBegin, EntryBB); | |||
716 | SrcElementCurrent = | |||
717 | Address(SrcElementPHI, SrcAddr.getElementType(), | |||
718 | SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); | |||
719 | } | |||
720 | llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI( | |||
721 | DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); | |||
722 | DestElementPHI->addIncoming(DestBegin, EntryBB); | |||
723 | Address DestElementCurrent = | |||
724 | Address(DestElementPHI, DestAddr.getElementType(), | |||
725 | DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); | |||
726 | ||||
727 | // Emit copy. | |||
728 | { | |||
729 | CodeGenFunction::RunCleanupsScope InitScope(CGF); | |||
730 | if (EmitDeclareReductionInit) { | |||
731 | emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent, | |||
732 | SrcElementCurrent, ElementTy); | |||
733 | } else | |||
734 | CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(), | |||
735 | /*IsInitializer=*/false); | |||
736 | } | |||
737 | ||||
738 | if (DRD) { | |||
739 | // Shift the address forward by one element. | |||
740 | llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32( | |||
741 | SrcAddr.getElementType(), SrcElementPHI, /*Idx0=*/1, | |||
742 | "omp.arraycpy.dest.element"); | |||
743 | SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock()); | |||
744 | } | |||
745 | ||||
746 | // Shift the address forward by one element. | |||
747 | llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32( | |||
748 | DestAddr.getElementType(), DestElementPHI, /*Idx0=*/1, | |||
749 | "omp.arraycpy.dest.element"); | |||
750 | // Check whether we've reached the end. | |||
751 | llvm::Value *Done = | |||
752 | CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); | |||
753 | CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB); | |||
754 | DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock()); | |||
755 | ||||
756 | // Done. | |||
757 | CGF.EmitBlock(DoneBB, /*IsFinished=*/true); | |||
758 | } | |||
759 | ||||
760 | LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) { | |||
761 | return CGF.EmitOMPSharedLValue(E); | |||
762 | } | |||
763 | ||||
764 | LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF, | |||
765 | const Expr *E) { | |||
766 | if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E)) | |||
767 | return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false); | |||
768 | return LValue(); | |||
769 | } | |||
770 | ||||
771 | void ReductionCodeGen::emitAggregateInitialization( | |||
772 | CodeGenFunction &CGF, unsigned N, Address PrivateAddr, Address SharedAddr, | |||
773 | const OMPDeclareReductionDecl *DRD) { | |||
774 | // Emit VarDecl with copy init for arrays. | |||
775 | // Get the address of the original variable captured in current | |||
776 | // captured region. | |||
777 | const auto *PrivateVD = | |||
778 | cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); | |||
779 | bool EmitDeclareReductionInit = | |||
780 | DRD && (DRD->getInitializer() || !PrivateVD->hasInit()); | |||
781 | EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(), | |||
782 | EmitDeclareReductionInit, | |||
783 | EmitDeclareReductionInit ? ClausesData[N].ReductionOp | |||
784 | : PrivateVD->getInit(), | |||
785 | DRD, SharedAddr); | |||
786 | } | |||
787 | ||||
788 | ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds, | |||
789 | ArrayRef<const Expr *> Origs, | |||
790 | ArrayRef<const Expr *> Privates, | |||
791 | ArrayRef<const Expr *> ReductionOps) { | |||
792 | ClausesData.reserve(Shareds.size()); | |||
793 | SharedAddresses.reserve(Shareds.size()); | |||
794 | Sizes.reserve(Shareds.size()); | |||
795 | BaseDecls.reserve(Shareds.size()); | |||
796 | const auto *IOrig = Origs.begin(); | |||
797 | const auto *IPriv = Privates.begin(); | |||
798 | const auto *IRed = ReductionOps.begin(); | |||
799 | for (const Expr *Ref : Shareds) { | |||
800 | ClausesData.emplace_back(Ref, *IOrig, *IPriv, *IRed); | |||
801 | std::advance(IOrig, 1); | |||
802 | std::advance(IPriv, 1); | |||
803 | std::advance(IRed, 1); | |||
804 | } | |||
805 | } | |||
806 | ||||
807 | void ReductionCodeGen::emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N) { | |||
808 | assert(SharedAddresses.size() == N && OrigAddresses.size() == N &&(static_cast <bool> (SharedAddresses.size() == N && OrigAddresses.size() == N && "Number of generated lvalues must be exactly N." ) ? void (0) : __assert_fail ("SharedAddresses.size() == N && OrigAddresses.size() == N && \"Number of generated lvalues must be exactly N.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 809, __extension__ __PRETTY_FUNCTION__)) | |||
809 | "Number of generated lvalues must be exactly N.")(static_cast <bool> (SharedAddresses.size() == N && OrigAddresses.size() == N && "Number of generated lvalues must be exactly N." ) ? void (0) : __assert_fail ("SharedAddresses.size() == N && OrigAddresses.size() == N && \"Number of generated lvalues must be exactly N.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 809, __extension__ __PRETTY_FUNCTION__)); | |||
810 | LValue First = emitSharedLValue(CGF, ClausesData[N].Shared); | |||
811 | LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Shared); | |||
812 | SharedAddresses.emplace_back(First, Second); | |||
813 | if (ClausesData[N].Shared == ClausesData[N].Ref) { | |||
814 | OrigAddresses.emplace_back(First, Second); | |||
815 | } else { | |||
816 | LValue First = emitSharedLValue(CGF, ClausesData[N].Ref); | |||
817 | LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref); | |||
818 | OrigAddresses.emplace_back(First, Second); | |||
819 | } | |||
820 | } | |||
821 | ||||
822 | void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) { | |||
823 | QualType PrivateType = getPrivateType(N); | |||
824 | bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref); | |||
825 | if (!PrivateType->isVariablyModifiedType()) { | |||
826 | Sizes.emplace_back( | |||
827 | CGF.getTypeSize(OrigAddresses[N].first.getType().getNonReferenceType()), | |||
828 | nullptr); | |||
829 | return; | |||
830 | } | |||
831 | llvm::Value *Size; | |||
832 | llvm::Value *SizeInChars; | |||
833 | auto *ElemType = OrigAddresses[N].first.getAddress(CGF).getElementType(); | |||
834 | auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType); | |||
835 | if (AsArraySection) { | |||
836 | Size = CGF.Builder.CreatePtrDiff(ElemType, | |||
837 | OrigAddresses[N].second.getPointer(CGF), | |||
838 | OrigAddresses[N].first.getPointer(CGF)); | |||
839 | Size = CGF.Builder.CreateNUWAdd( | |||
840 | Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1)); | |||
841 | SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf); | |||
842 | } else { | |||
843 | SizeInChars = | |||
844 | CGF.getTypeSize(OrigAddresses[N].first.getType().getNonReferenceType()); | |||
845 | Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf); | |||
846 | } | |||
847 | Sizes.emplace_back(SizeInChars, Size); | |||
848 | CodeGenFunction::OpaqueValueMapping OpaqueMap( | |||
849 | CGF, | |||
850 | cast<OpaqueValueExpr>( | |||
851 | CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()), | |||
852 | RValue::get(Size)); | |||
853 | CGF.EmitVariablyModifiedType(PrivateType); | |||
854 | } | |||
855 | ||||
856 | void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N, | |||
857 | llvm::Value *Size) { | |||
858 | QualType PrivateType = getPrivateType(N); | |||
859 | if (!PrivateType->isVariablyModifiedType()) { | |||
860 | assert(!Size && !Sizes[N].second &&(static_cast <bool> (!Size && !Sizes[N].second && "Size should be nullptr for non-variably modified reduction " "items.") ? void (0) : __assert_fail ("!Size && !Sizes[N].second && \"Size should be nullptr for non-variably modified reduction \" \"items.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 862, __extension__ __PRETTY_FUNCTION__)) | |||
861 | "Size should be nullptr for non-variably modified reduction "(static_cast <bool> (!Size && !Sizes[N].second && "Size should be nullptr for non-variably modified reduction " "items.") ? void (0) : __assert_fail ("!Size && !Sizes[N].second && \"Size should be nullptr for non-variably modified reduction \" \"items.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 862, __extension__ __PRETTY_FUNCTION__)) | |||
862 | "items.")(static_cast <bool> (!Size && !Sizes[N].second && "Size should be nullptr for non-variably modified reduction " "items.") ? void (0) : __assert_fail ("!Size && !Sizes[N].second && \"Size should be nullptr for non-variably modified reduction \" \"items.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 862, __extension__ __PRETTY_FUNCTION__)); | |||
863 | return; | |||
864 | } | |||
865 | CodeGenFunction::OpaqueValueMapping OpaqueMap( | |||
866 | CGF, | |||
867 | cast<OpaqueValueExpr>( | |||
868 | CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()), | |||
869 | RValue::get(Size)); | |||
870 | CGF.EmitVariablyModifiedType(PrivateType); | |||
871 | } | |||
872 | ||||
873 | void ReductionCodeGen::emitInitialization( | |||
874 | CodeGenFunction &CGF, unsigned N, Address PrivateAddr, Address SharedAddr, | |||
875 | llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) { | |||
876 | assert(SharedAddresses.size() > N && "No variable was generated")(static_cast <bool> (SharedAddresses.size() > N && "No variable was generated") ? void (0) : __assert_fail ("SharedAddresses.size() > N && \"No variable was generated\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 876, __extension__ __PRETTY_FUNCTION__)); | |||
877 | const auto *PrivateVD = | |||
878 | cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); | |||
879 | const OMPDeclareReductionDecl *DRD = | |||
880 | getReductionInit(ClausesData[N].ReductionOp); | |||
881 | if (CGF.getContext().getAsArrayType(PrivateVD->getType())) { | |||
882 | if (DRD && DRD->getInitializer()) | |||
883 | (void)DefaultInit(CGF); | |||
884 | emitAggregateInitialization(CGF, N, PrivateAddr, SharedAddr, DRD); | |||
885 | } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) { | |||
886 | (void)DefaultInit(CGF); | |||
887 | QualType SharedType = SharedAddresses[N].first.getType(); | |||
888 | emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp, | |||
889 | PrivateAddr, SharedAddr, SharedType); | |||
890 | } else if (!DefaultInit(CGF) && PrivateVD->hasInit() && | |||
891 | !CGF.isTrivialInitializer(PrivateVD->getInit())) { | |||
892 | CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr, | |||
893 | PrivateVD->getType().getQualifiers(), | |||
894 | /*IsInitializer=*/false); | |||
895 | } | |||
896 | } | |||
897 | ||||
898 | bool ReductionCodeGen::needCleanups(unsigned N) { | |||
899 | QualType PrivateType = getPrivateType(N); | |||
900 | QualType::DestructionKind DTorKind = PrivateType.isDestructedType(); | |||
901 | return DTorKind != QualType::DK_none; | |||
902 | } | |||
903 | ||||
904 | void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N, | |||
905 | Address PrivateAddr) { | |||
906 | QualType PrivateType = getPrivateType(N); | |||
907 | QualType::DestructionKind DTorKind = PrivateType.isDestructedType(); | |||
908 | if (needCleanups(N)) { | |||
909 | PrivateAddr = CGF.Builder.CreateElementBitCast( | |||
910 | PrivateAddr, CGF.ConvertTypeForMem(PrivateType)); | |||
911 | CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType); | |||
912 | } | |||
913 | } | |||
914 | ||||
915 | static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, | |||
916 | LValue BaseLV) { | |||
917 | BaseTy = BaseTy.getNonReferenceType(); | |||
918 | while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && | |||
919 | !CGF.getContext().hasSameType(BaseTy, ElTy)) { | |||
920 | if (const auto *PtrTy = BaseTy->getAs<PointerType>()) { | |||
921 | BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(CGF), PtrTy); | |||
922 | } else { | |||
923 | LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(CGF), BaseTy); | |||
924 | BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal); | |||
925 | } | |||
926 | BaseTy = BaseTy->getPointeeType(); | |||
927 | } | |||
928 | return CGF.MakeAddrLValue( | |||
929 | CGF.Builder.CreateElementBitCast(BaseLV.getAddress(CGF), | |||
930 | CGF.ConvertTypeForMem(ElTy)), | |||
931 | BaseLV.getType(), BaseLV.getBaseInfo(), | |||
932 | CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType())); | |||
933 | } | |||
934 | ||||
935 | static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, | |||
936 | Address OriginalBaseAddress, llvm::Value *Addr) { | |||
937 | Address Tmp = Address::invalid(); | |||
938 | Address TopTmp = Address::invalid(); | |||
939 | Address MostTopTmp = Address::invalid(); | |||
940 | BaseTy = BaseTy.getNonReferenceType(); | |||
941 | while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && | |||
942 | !CGF.getContext().hasSameType(BaseTy, ElTy)) { | |||
943 | Tmp = CGF.CreateMemTemp(BaseTy); | |||
944 | if (TopTmp.isValid()) | |||
945 | CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp); | |||
946 | else | |||
947 | MostTopTmp = Tmp; | |||
948 | TopTmp = Tmp; | |||
949 | BaseTy = BaseTy->getPointeeType(); | |||
950 | } | |||
951 | ||||
952 | if (Tmp.isValid()) { | |||
953 | Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
954 | Addr, Tmp.getElementType()); | |||
955 | CGF.Builder.CreateStore(Addr, Tmp); | |||
956 | return MostTopTmp; | |||
957 | } | |||
958 | ||||
959 | Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
960 | Addr, OriginalBaseAddress.getType()); | |||
961 | return OriginalBaseAddress.withPointer(Addr, NotKnownNonNull); | |||
962 | } | |||
963 | ||||
964 | static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) { | |||
965 | const VarDecl *OrigVD = nullptr; | |||
966 | if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) { | |||
967 | const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); | |||
968 | while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) | |||
969 | Base = TempOASE->getBase()->IgnoreParenImpCasts(); | |||
970 | while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) | |||
971 | Base = TempASE->getBase()->IgnoreParenImpCasts(); | |||
972 | DE = cast<DeclRefExpr>(Base); | |||
973 | OrigVD = cast<VarDecl>(DE->getDecl()); | |||
974 | } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) { | |||
975 | const Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); | |||
976 | while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) | |||
977 | Base = TempASE->getBase()->IgnoreParenImpCasts(); | |||
978 | DE = cast<DeclRefExpr>(Base); | |||
979 | OrigVD = cast<VarDecl>(DE->getDecl()); | |||
980 | } | |||
981 | return OrigVD; | |||
982 | } | |||
983 | ||||
984 | Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, | |||
985 | Address PrivateAddr) { | |||
986 | const DeclRefExpr *DE; | |||
987 | if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) { | |||
988 | BaseDecls.emplace_back(OrigVD); | |||
989 | LValue OriginalBaseLValue = CGF.EmitLValue(DE); | |||
990 | LValue BaseLValue = | |||
991 | loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(), | |||
992 | OriginalBaseLValue); | |||
993 | Address SharedAddr = SharedAddresses[N].first.getAddress(CGF); | |||
994 | llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff( | |||
995 | SharedAddr.getElementType(), BaseLValue.getPointer(CGF), | |||
996 | SharedAddr.getPointer()); | |||
997 | llvm::Value *PrivatePointer = | |||
998 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
999 | PrivateAddr.getPointer(), SharedAddr.getType()); | |||
1000 | llvm::Value *Ptr = CGF.Builder.CreateGEP( | |||
1001 | SharedAddr.getElementType(), PrivatePointer, Adjustment); | |||
1002 | return castToBase(CGF, OrigVD->getType(), | |||
1003 | SharedAddresses[N].first.getType(), | |||
1004 | OriginalBaseLValue.getAddress(CGF), Ptr); | |||
1005 | } | |||
1006 | BaseDecls.emplace_back( | |||
1007 | cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl())); | |||
1008 | return PrivateAddr; | |||
1009 | } | |||
1010 | ||||
1011 | bool ReductionCodeGen::usesReductionInitializer(unsigned N) const { | |||
1012 | const OMPDeclareReductionDecl *DRD = | |||
1013 | getReductionInit(ClausesData[N].ReductionOp); | |||
1014 | return DRD && DRD->getInitializer(); | |||
1015 | } | |||
1016 | ||||
1017 | LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) { | |||
1018 | return CGF.EmitLoadOfPointerLValue( | |||
1019 | CGF.GetAddrOfLocalVar(getThreadIDVariable()), | |||
1020 | getThreadIDVariable()->getType()->castAs<PointerType>()); | |||
1021 | } | |||
1022 | ||||
1023 | void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt *S) { | |||
1024 | if (!CGF.HaveInsertPoint()) | |||
1025 | return; | |||
1026 | // 1.2.2 OpenMP Language Terminology | |||
1027 | // Structured block - An executable statement with a single entry at the | |||
1028 | // top and a single exit at the bottom. | |||
1029 | // The point of exit cannot be a branch out of the structured block. | |||
1030 | // longjmp() and throw() must not violate the entry/exit criteria. | |||
1031 | CGF.EHStack.pushTerminate(); | |||
1032 | if (S) | |||
1033 | CGF.incrementProfileCounter(S); | |||
1034 | CodeGen(CGF); | |||
1035 | CGF.EHStack.popTerminate(); | |||
1036 | } | |||
1037 | ||||
1038 | LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue( | |||
1039 | CodeGenFunction &CGF) { | |||
1040 | return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()), | |||
1041 | getThreadIDVariable()->getType(), | |||
1042 | AlignmentSource::Decl); | |||
1043 | } | |||
1044 | ||||
1045 | static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC, | |||
1046 | QualType FieldTy) { | |||
1047 | auto *Field = FieldDecl::Create( | |||
1048 | C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy, | |||
1049 | C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()), | |||
1050 | /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit); | |||
1051 | Field->setAccess(AS_public); | |||
1052 | DC->addDecl(Field); | |||
1053 | return Field; | |||
1054 | } | |||
1055 | ||||
1056 | CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM) | |||
1057 | : CGM(CGM), OMPBuilder(CGM.getModule()) { | |||
1058 | KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8); | |||
1059 | llvm::OpenMPIRBuilderConfig Config(CGM.getLangOpts().OpenMPIsDevice, false, | |||
1060 | hasRequiresUnifiedSharedMemory(), | |||
1061 | CGM.getLangOpts().OpenMPOffloadMandatory); | |||
1062 | // Initialize Types used in OpenMPIRBuilder from OMPKinds.def | |||
1063 | OMPBuilder.initialize(); | |||
1064 | OMPBuilder.setConfig(Config); | |||
1065 | loadOffloadInfoMetadata(); | |||
1066 | } | |||
1067 | ||||
1068 | void CGOpenMPRuntime::clear() { | |||
1069 | InternalVars.clear(); | |||
1070 | // Clean non-target variable declarations possibly used only in debug info. | |||
1071 | for (const auto &Data : EmittedNonTargetVariables) { | |||
1072 | if (!Data.getValue().pointsToAliveValue()) | |||
1073 | continue; | |||
1074 | auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue()); | |||
1075 | if (!GV) | |||
1076 | continue; | |||
1077 | if (!GV->isDeclaration() || GV->getNumUses() > 0) | |||
1078 | continue; | |||
1079 | GV->eraseFromParent(); | |||
1080 | } | |||
1081 | } | |||
1082 | ||||
1083 | std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const { | |||
1084 | return OMPBuilder.createPlatformSpecificName(Parts); | |||
1085 | } | |||
1086 | ||||
1087 | static llvm::Function * | |||
1088 | emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty, | |||
1089 | const Expr *CombinerInitializer, const VarDecl *In, | |||
1090 | const VarDecl *Out, bool IsCombiner) { | |||
1091 | // void .omp_combiner.(Ty *in, Ty *out); | |||
1092 | ASTContext &C = CGM.getContext(); | |||
1093 | QualType PtrTy = C.getPointerType(Ty).withRestrict(); | |||
1094 | FunctionArgList Args; | |||
1095 | ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(), | |||
1096 | /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other); | |||
1097 | ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(), | |||
1098 | /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other); | |||
1099 | Args.push_back(&OmpOutParm); | |||
1100 | Args.push_back(&OmpInParm); | |||
1101 | const CGFunctionInfo &FnInfo = | |||
1102 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
1103 | llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); | |||
1104 | std::string Name = CGM.getOpenMPRuntime().getName( | |||
1105 | {IsCombiner ? "omp_combiner" : "omp_initializer", ""}); | |||
1106 | auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, | |||
1107 | Name, &CGM.getModule()); | |||
1108 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); | |||
1109 | if (CGM.getLangOpts().Optimize) { | |||
1110 | Fn->removeFnAttr(llvm::Attribute::NoInline); | |||
1111 | Fn->removeFnAttr(llvm::Attribute::OptimizeNone); | |||
1112 | Fn->addFnAttr(llvm::Attribute::AlwaysInline); | |||
1113 | } | |||
1114 | CodeGenFunction CGF(CGM); | |||
1115 | // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions. | |||
1116 | // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions. | |||
1117 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(), | |||
1118 | Out->getLocation()); | |||
1119 | CodeGenFunction::OMPPrivateScope Scope(CGF); | |||
1120 | Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm); | |||
1121 | Scope.addPrivate( | |||
1122 | In, CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>()) | |||
1123 | .getAddress(CGF)); | |||
1124 | Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm); | |||
1125 | Scope.addPrivate( | |||
1126 | Out, CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>()) | |||
1127 | .getAddress(CGF)); | |||
1128 | (void)Scope.Privatize(); | |||
1129 | if (!IsCombiner && Out->hasInit() && | |||
1130 | !CGF.isTrivialInitializer(Out->getInit())) { | |||
1131 | CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out), | |||
1132 | Out->getType().getQualifiers(), | |||
1133 | /*IsInitializer=*/true); | |||
1134 | } | |||
1135 | if (CombinerInitializer) | |||
1136 | CGF.EmitIgnoredExpr(CombinerInitializer); | |||
1137 | Scope.ForceCleanup(); | |||
1138 | CGF.FinishFunction(); | |||
1139 | return Fn; | |||
1140 | } | |||
1141 | ||||
1142 | void CGOpenMPRuntime::emitUserDefinedReduction( | |||
1143 | CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) { | |||
1144 | if (UDRMap.count(D) > 0) | |||
1145 | return; | |||
1146 | llvm::Function *Combiner = emitCombinerOrInitializer( | |||
1147 | CGM, D->getType(), D->getCombiner(), | |||
1148 | cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()), | |||
1149 | cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()), | |||
1150 | /*IsCombiner=*/true); | |||
1151 | llvm::Function *Initializer = nullptr; | |||
1152 | if (const Expr *Init = D->getInitializer()) { | |||
1153 | Initializer = emitCombinerOrInitializer( | |||
1154 | CGM, D->getType(), | |||
1155 | D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init | |||
1156 | : nullptr, | |||
1157 | cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()), | |||
1158 | cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()), | |||
1159 | /*IsCombiner=*/false); | |||
1160 | } | |||
1161 | UDRMap.try_emplace(D, Combiner, Initializer); | |||
1162 | if (CGF) { | |||
1163 | auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn); | |||
1164 | Decls.second.push_back(D); | |||
1165 | } | |||
1166 | } | |||
1167 | ||||
1168 | std::pair<llvm::Function *, llvm::Function *> | |||
1169 | CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) { | |||
1170 | auto I = UDRMap.find(D); | |||
1171 | if (I != UDRMap.end()) | |||
1172 | return I->second; | |||
1173 | emitUserDefinedReduction(/*CGF=*/nullptr, D); | |||
1174 | return UDRMap.lookup(D); | |||
1175 | } | |||
1176 | ||||
1177 | namespace { | |||
1178 | // Temporary RAII solution to perform a push/pop stack event on the OpenMP IR | |||
1179 | // Builder if one is present. | |||
1180 | struct PushAndPopStackRAII { | |||
1181 | PushAndPopStackRAII(llvm::OpenMPIRBuilder *OMPBuilder, CodeGenFunction &CGF, | |||
1182 | bool HasCancel, llvm::omp::Directive Kind) | |||
1183 | : OMPBuilder(OMPBuilder) { | |||
1184 | if (!OMPBuilder) | |||
1185 | return; | |||
1186 | ||||
1187 | // The following callback is the crucial part of clangs cleanup process. | |||
1188 | // | |||
1189 | // NOTE: | |||
1190 | // Once the OpenMPIRBuilder is used to create parallel regions (and | |||
1191 | // similar), the cancellation destination (Dest below) is determined via | |||
1192 | // IP. That means if we have variables to finalize we split the block at IP, | |||
1193 | // use the new block (=BB) as destination to build a JumpDest (via | |||
1194 | // getJumpDestInCurrentScope(BB)) which then is fed to | |||
1195 | // EmitBranchThroughCleanup. Furthermore, there will not be the need | |||
1196 | // to push & pop an FinalizationInfo object. | |||
1197 | // The FiniCB will still be needed but at the point where the | |||
1198 | // OpenMPIRBuilder is asked to construct a parallel (or similar) construct. | |||
1199 | auto FiniCB = [&CGF](llvm::OpenMPIRBuilder::InsertPointTy IP) { | |||
1200 | assert(IP.getBlock()->end() == IP.getPoint() &&(static_cast <bool> (IP.getBlock()->end() == IP.getPoint () && "Clang CG should cause non-terminated block!") ? void (0) : __assert_fail ("IP.getBlock()->end() == IP.getPoint() && \"Clang CG should cause non-terminated block!\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1201, __extension__ __PRETTY_FUNCTION__)) | |||
1201 | "Clang CG should cause non-terminated block!")(static_cast <bool> (IP.getBlock()->end() == IP.getPoint () && "Clang CG should cause non-terminated block!") ? void (0) : __assert_fail ("IP.getBlock()->end() == IP.getPoint() && \"Clang CG should cause non-terminated block!\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1201, __extension__ __PRETTY_FUNCTION__)); | |||
1202 | CGBuilderTy::InsertPointGuard IPG(CGF.Builder); | |||
1203 | CGF.Builder.restoreIP(IP); | |||
1204 | CodeGenFunction::JumpDest Dest = | |||
1205 | CGF.getOMPCancelDestination(OMPD_parallel); | |||
1206 | CGF.EmitBranchThroughCleanup(Dest); | |||
1207 | }; | |||
1208 | ||||
1209 | // TODO: Remove this once we emit parallel regions through the | |||
1210 | // OpenMPIRBuilder as it can do this setup internally. | |||
1211 | llvm::OpenMPIRBuilder::FinalizationInfo FI({FiniCB, Kind, HasCancel}); | |||
1212 | OMPBuilder->pushFinalizationCB(std::move(FI)); | |||
1213 | } | |||
1214 | ~PushAndPopStackRAII() { | |||
1215 | if (OMPBuilder) | |||
1216 | OMPBuilder->popFinalizationCB(); | |||
1217 | } | |||
1218 | llvm::OpenMPIRBuilder *OMPBuilder; | |||
1219 | }; | |||
1220 | } // namespace | |||
1221 | ||||
1222 | static llvm::Function *emitParallelOrTeamsOutlinedFunction( | |||
1223 | CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS, | |||
1224 | const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, | |||
1225 | const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) { | |||
1226 | assert(ThreadIDVar->getType()->isPointerType() &&(static_cast <bool> (ThreadIDVar->getType()->isPointerType () && "thread id variable must be of type kmp_int32 *" ) ? void (0) : __assert_fail ("ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 *\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1227, __extension__ __PRETTY_FUNCTION__)) | |||
1227 | "thread id variable must be of type kmp_int32 *")(static_cast <bool> (ThreadIDVar->getType()->isPointerType () && "thread id variable must be of type kmp_int32 *" ) ? void (0) : __assert_fail ("ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 *\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1227, __extension__ __PRETTY_FUNCTION__)); | |||
1228 | CodeGenFunction CGF(CGM, true); | |||
1229 | bool HasCancel = false; | |||
1230 | if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D)) | |||
1231 | HasCancel = OPD->hasCancel(); | |||
1232 | else if (const auto *OPD = dyn_cast<OMPTargetParallelDirective>(&D)) | |||
1233 | HasCancel = OPD->hasCancel(); | |||
1234 | else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D)) | |||
1235 | HasCancel = OPSD->hasCancel(); | |||
1236 | else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D)) | |||
1237 | HasCancel = OPFD->hasCancel(); | |||
1238 | else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D)) | |||
1239 | HasCancel = OPFD->hasCancel(); | |||
1240 | else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D)) | |||
1241 | HasCancel = OPFD->hasCancel(); | |||
1242 | else if (const auto *OPFD = | |||
1243 | dyn_cast<OMPTeamsDistributeParallelForDirective>(&D)) | |||
1244 | HasCancel = OPFD->hasCancel(); | |||
1245 | else if (const auto *OPFD = | |||
1246 | dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D)) | |||
1247 | HasCancel = OPFD->hasCancel(); | |||
1248 | ||||
1249 | // TODO: Temporarily inform the OpenMPIRBuilder, if any, about the new | |||
1250 | // parallel region to make cancellation barriers work properly. | |||
1251 | llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); | |||
1252 | PushAndPopStackRAII PSR(&OMPBuilder, CGF, HasCancel, InnermostKind); | |||
1253 | CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind, | |||
1254 | HasCancel, OutlinedHelperName); | |||
1255 | CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); | |||
1256 | return CGF.GenerateOpenMPCapturedStmtFunction(*CS, D.getBeginLoc()); | |||
1257 | } | |||
1258 | ||||
1259 | llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction( | |||
1260 | const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, | |||
1261 | OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { | |||
1262 | const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel); | |||
1263 | return emitParallelOrTeamsOutlinedFunction( | |||
1264 | CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen); | |||
1265 | } | |||
1266 | ||||
1267 | llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction( | |||
1268 | const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, | |||
1269 | OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { | |||
1270 | const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams); | |||
1271 | return emitParallelOrTeamsOutlinedFunction( | |||
1272 | CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen); | |||
1273 | } | |||
1274 | ||||
1275 | llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction( | |||
1276 | const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, | |||
1277 | const VarDecl *PartIDVar, const VarDecl *TaskTVar, | |||
1278 | OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, | |||
1279 | bool Tied, unsigned &NumberOfParts) { | |||
1280 | auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF, | |||
1281 | PrePostActionTy &) { | |||
1282 | llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc()); | |||
1283 | llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc()); | |||
1284 | llvm::Value *TaskArgs[] = { | |||
1285 | UpLoc, ThreadID, | |||
1286 | CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar), | |||
1287 | TaskTVar->getType()->castAs<PointerType>()) | |||
1288 | .getPointer(CGF)}; | |||
1289 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
1290 | CGM.getModule(), OMPRTL___kmpc_omp_task), | |||
1291 | TaskArgs); | |||
1292 | }; | |||
1293 | CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar, | |||
1294 | UntiedCodeGen); | |||
1295 | CodeGen.setAction(Action); | |||
1296 | assert(!ThreadIDVar->getType()->isPointerType() &&(static_cast <bool> (!ThreadIDVar->getType()->isPointerType () && "thread id variable must be of type kmp_int32 for tasks" ) ? void (0) : __assert_fail ("!ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 for tasks\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1297, __extension__ __PRETTY_FUNCTION__)) | |||
1297 | "thread id variable must be of type kmp_int32 for tasks")(static_cast <bool> (!ThreadIDVar->getType()->isPointerType () && "thread id variable must be of type kmp_int32 for tasks" ) ? void (0) : __assert_fail ("!ThreadIDVar->getType()->isPointerType() && \"thread id variable must be of type kmp_int32 for tasks\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1297, __extension__ __PRETTY_FUNCTION__)); | |||
1298 | const OpenMPDirectiveKind Region = | |||
1299 | isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop | |||
1300 | : OMPD_task; | |||
1301 | const CapturedStmt *CS = D.getCapturedStmt(Region); | |||
1302 | bool HasCancel = false; | |||
1303 | if (const auto *TD = dyn_cast<OMPTaskDirective>(&D)) | |||
1304 | HasCancel = TD->hasCancel(); | |||
1305 | else if (const auto *TD = dyn_cast<OMPTaskLoopDirective>(&D)) | |||
1306 | HasCancel = TD->hasCancel(); | |||
1307 | else if (const auto *TD = dyn_cast<OMPMasterTaskLoopDirective>(&D)) | |||
1308 | HasCancel = TD->hasCancel(); | |||
1309 | else if (const auto *TD = dyn_cast<OMPParallelMasterTaskLoopDirective>(&D)) | |||
1310 | HasCancel = TD->hasCancel(); | |||
1311 | ||||
1312 | CodeGenFunction CGF(CGM, true); | |||
1313 | CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, | |||
1314 | InnermostKind, HasCancel, Action); | |||
1315 | CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); | |||
1316 | llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS); | |||
1317 | if (!Tied) | |||
1318 | NumberOfParts = Action.getNumberOfParts(); | |||
1319 | return Res; | |||
1320 | } | |||
1321 | ||||
1322 | void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF, | |||
1323 | bool AtCurrentPoint) { | |||
1324 | auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); | |||
1325 | assert(!Elem.second.ServiceInsertPt && "Insert point is set already.")(static_cast <bool> (!Elem.second.ServiceInsertPt && "Insert point is set already.") ? void (0) : __assert_fail ( "!Elem.second.ServiceInsertPt && \"Insert point is set already.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1325, __extension__ __PRETTY_FUNCTION__)); | |||
1326 | ||||
1327 | llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty); | |||
1328 | if (AtCurrentPoint) { | |||
1329 | Elem.second.ServiceInsertPt = new llvm::BitCastInst( | |||
1330 | Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock()); | |||
1331 | } else { | |||
1332 | Elem.second.ServiceInsertPt = | |||
1333 | new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt"); | |||
1334 | Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt); | |||
1335 | } | |||
1336 | } | |||
1337 | ||||
1338 | void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) { | |||
1339 | auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); | |||
1340 | if (Elem.second.ServiceInsertPt) { | |||
1341 | llvm::Instruction *Ptr = Elem.second.ServiceInsertPt; | |||
1342 | Elem.second.ServiceInsertPt = nullptr; | |||
1343 | Ptr->eraseFromParent(); | |||
1344 | } | |||
1345 | } | |||
1346 | ||||
1347 | static StringRef getIdentStringFromSourceLocation(CodeGenFunction &CGF, | |||
1348 | SourceLocation Loc, | |||
1349 | SmallString<128> &Buffer) { | |||
1350 | llvm::raw_svector_ostream OS(Buffer); | |||
1351 | // Build debug location | |||
1352 | PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc); | |||
1353 | OS << ";" << PLoc.getFilename() << ";"; | |||
1354 | if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) | |||
1355 | OS << FD->getQualifiedNameAsString(); | |||
1356 | OS << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;"; | |||
1357 | return OS.str(); | |||
1358 | } | |||
1359 | ||||
1360 | llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF, | |||
1361 | SourceLocation Loc, | |||
1362 | unsigned Flags, bool EmitLoc) { | |||
1363 | uint32_t SrcLocStrSize; | |||
1364 | llvm::Constant *SrcLocStr; | |||
1365 | if ((!EmitLoc && CGM.getCodeGenOpts().getDebugInfo() == | |||
1366 | llvm::codegenoptions::NoDebugInfo) || | |||
1367 | Loc.isInvalid()) { | |||
1368 | SrcLocStr = OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize); | |||
1369 | } else { | |||
1370 | std::string FunctionName; | |||
1371 | if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) | |||
1372 | FunctionName = FD->getQualifiedNameAsString(); | |||
1373 | PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc); | |||
1374 | const char *FileName = PLoc.getFilename(); | |||
1375 | unsigned Line = PLoc.getLine(); | |||
1376 | unsigned Column = PLoc.getColumn(); | |||
1377 | SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(FunctionName, FileName, Line, | |||
1378 | Column, SrcLocStrSize); | |||
1379 | } | |||
1380 | unsigned Reserved2Flags = getDefaultLocationReserved2Flags(); | |||
1381 | return OMPBuilder.getOrCreateIdent( | |||
1382 | SrcLocStr, SrcLocStrSize, llvm::omp::IdentFlag(Flags), Reserved2Flags); | |||
1383 | } | |||
1384 | ||||
1385 | llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF, | |||
1386 | SourceLocation Loc) { | |||
1387 | assert(CGF.CurFn && "No function in current CodeGenFunction.")(static_cast <bool> (CGF.CurFn && "No function in current CodeGenFunction." ) ? void (0) : __assert_fail ("CGF.CurFn && \"No function in current CodeGenFunction.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1387, __extension__ __PRETTY_FUNCTION__)); | |||
1388 | // If the OpenMPIRBuilder is used we need to use it for all thread id calls as | |||
1389 | // the clang invariants used below might be broken. | |||
1390 | if (CGM.getLangOpts().OpenMPIRBuilder) { | |||
1391 | SmallString<128> Buffer; | |||
1392 | OMPBuilder.updateToLocation(CGF.Builder.saveIP()); | |||
1393 | uint32_t SrcLocStrSize; | |||
1394 | auto *SrcLocStr = OMPBuilder.getOrCreateSrcLocStr( | |||
1395 | getIdentStringFromSourceLocation(CGF, Loc, Buffer), SrcLocStrSize); | |||
1396 | return OMPBuilder.getOrCreateThreadID( | |||
1397 | OMPBuilder.getOrCreateIdent(SrcLocStr, SrcLocStrSize)); | |||
1398 | } | |||
1399 | ||||
1400 | llvm::Value *ThreadID = nullptr; | |||
1401 | // Check whether we've already cached a load of the thread id in this | |||
1402 | // function. | |||
1403 | auto I = OpenMPLocThreadIDMap.find(CGF.CurFn); | |||
1404 | if (I != OpenMPLocThreadIDMap.end()) { | |||
1405 | ThreadID = I->second.ThreadID; | |||
1406 | if (ThreadID != nullptr) | |||
1407 | return ThreadID; | |||
1408 | } | |||
1409 | // If exceptions are enabled, do not use parameter to avoid possible crash. | |||
1410 | if (auto *OMPRegionInfo = | |||
1411 | dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { | |||
1412 | if (OMPRegionInfo->getThreadIDVariable()) { | |||
1413 | // Check if this an outlined function with thread id passed as argument. | |||
1414 | LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF); | |||
1415 | llvm::BasicBlock *TopBlock = CGF.AllocaInsertPt->getParent(); | |||
1416 | if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions || | |||
1417 | !CGF.getLangOpts().CXXExceptions || | |||
1418 | CGF.Builder.GetInsertBlock() == TopBlock || | |||
1419 | !isa<llvm::Instruction>(LVal.getPointer(CGF)) || | |||
1420 | cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() == | |||
1421 | TopBlock || | |||
1422 | cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() == | |||
1423 | CGF.Builder.GetInsertBlock()) { | |||
1424 | ThreadID = CGF.EmitLoadOfScalar(LVal, Loc); | |||
1425 | // If value loaded in entry block, cache it and use it everywhere in | |||
1426 | // function. | |||
1427 | if (CGF.Builder.GetInsertBlock() == TopBlock) { | |||
1428 | auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); | |||
1429 | Elem.second.ThreadID = ThreadID; | |||
1430 | } | |||
1431 | return ThreadID; | |||
1432 | } | |||
1433 | } | |||
1434 | } | |||
1435 | ||||
1436 | // This is not an outlined function region - need to call __kmpc_int32 | |||
1437 | // kmpc_global_thread_num(ident_t *loc). | |||
1438 | // Generate thread id value and cache this value for use across the | |||
1439 | // function. | |||
1440 | auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); | |||
1441 | if (!Elem.second.ServiceInsertPt) | |||
1442 | setLocThreadIdInsertPt(CGF); | |||
1443 | CGBuilderTy::InsertPointGuard IPG(CGF.Builder); | |||
1444 | CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt); | |||
1445 | llvm::CallInst *Call = CGF.Builder.CreateCall( | |||
1446 | OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), | |||
1447 | OMPRTL___kmpc_global_thread_num), | |||
1448 | emitUpdateLocation(CGF, Loc)); | |||
1449 | Call->setCallingConv(CGF.getRuntimeCC()); | |||
1450 | Elem.second.ThreadID = Call; | |||
1451 | return Call; | |||
1452 | } | |||
1453 | ||||
1454 | void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) { | |||
1455 | assert(CGF.CurFn && "No function in current CodeGenFunction.")(static_cast <bool> (CGF.CurFn && "No function in current CodeGenFunction." ) ? void (0) : __assert_fail ("CGF.CurFn && \"No function in current CodeGenFunction.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1455, __extension__ __PRETTY_FUNCTION__)); | |||
1456 | if (OpenMPLocThreadIDMap.count(CGF.CurFn)) { | |||
1457 | clearLocThreadIdInsertPt(CGF); | |||
1458 | OpenMPLocThreadIDMap.erase(CGF.CurFn); | |||
1459 | } | |||
1460 | if (FunctionUDRMap.count(CGF.CurFn) > 0) { | |||
1461 | for(const auto *D : FunctionUDRMap[CGF.CurFn]) | |||
1462 | UDRMap.erase(D); | |||
1463 | FunctionUDRMap.erase(CGF.CurFn); | |||
1464 | } | |||
1465 | auto I = FunctionUDMMap.find(CGF.CurFn); | |||
1466 | if (I != FunctionUDMMap.end()) { | |||
1467 | for(const auto *D : I->second) | |||
1468 | UDMMap.erase(D); | |||
1469 | FunctionUDMMap.erase(I); | |||
1470 | } | |||
1471 | LastprivateConditionalToTypes.erase(CGF.CurFn); | |||
1472 | FunctionToUntiedTaskStackMap.erase(CGF.CurFn); | |||
1473 | } | |||
1474 | ||||
1475 | llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() { | |||
1476 | return OMPBuilder.IdentPtr; | |||
1477 | } | |||
1478 | ||||
1479 | llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() { | |||
1480 | if (!Kmpc_MicroTy) { | |||
1481 | // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...) | |||
1482 | llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty), | |||
1483 | llvm::PointerType::getUnqual(CGM.Int32Ty)}; | |||
1484 | Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true); | |||
1485 | } | |||
1486 | return llvm::PointerType::getUnqual(Kmpc_MicroTy); | |||
1487 | } | |||
1488 | ||||
1489 | llvm::FunctionCallee | |||
1490 | CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned, | |||
1491 | bool IsGPUDistribute) { | |||
1492 | assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1493, __extension__ __PRETTY_FUNCTION__)) | |||
1493 | "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1493, __extension__ __PRETTY_FUNCTION__)); | |||
1494 | StringRef Name; | |||
1495 | if (IsGPUDistribute) | |||
1496 | Name = IVSize == 32 ? (IVSigned ? "__kmpc_distribute_static_init_4" | |||
1497 | : "__kmpc_distribute_static_init_4u") | |||
1498 | : (IVSigned ? "__kmpc_distribute_static_init_8" | |||
1499 | : "__kmpc_distribute_static_init_8u"); | |||
1500 | else | |||
1501 | Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4" | |||
1502 | : "__kmpc_for_static_init_4u") | |||
1503 | : (IVSigned ? "__kmpc_for_static_init_8" | |||
1504 | : "__kmpc_for_static_init_8u"); | |||
1505 | ||||
1506 | llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; | |||
1507 | auto *PtrTy = llvm::PointerType::getUnqual(ITy); | |||
1508 | llvm::Type *TypeParams[] = { | |||
1509 | getIdentTyPointerTy(), // loc | |||
1510 | CGM.Int32Ty, // tid | |||
1511 | CGM.Int32Ty, // schedtype | |||
1512 | llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter | |||
1513 | PtrTy, // p_lower | |||
1514 | PtrTy, // p_upper | |||
1515 | PtrTy, // p_stride | |||
1516 | ITy, // incr | |||
1517 | ITy // chunk | |||
1518 | }; | |||
1519 | auto *FnTy = | |||
1520 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); | |||
1521 | return CGM.CreateRuntimeFunction(FnTy, Name); | |||
1522 | } | |||
1523 | ||||
1524 | llvm::FunctionCallee | |||
1525 | CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) { | |||
1526 | assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1527, __extension__ __PRETTY_FUNCTION__)) | |||
1527 | "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1527, __extension__ __PRETTY_FUNCTION__)); | |||
1528 | StringRef Name = | |||
1529 | IVSize == 32 | |||
1530 | ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u") | |||
1531 | : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u"); | |||
1532 | llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; | |||
1533 | llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc | |||
1534 | CGM.Int32Ty, // tid | |||
1535 | CGM.Int32Ty, // schedtype | |||
1536 | ITy, // lower | |||
1537 | ITy, // upper | |||
1538 | ITy, // stride | |||
1539 | ITy // chunk | |||
1540 | }; | |||
1541 | auto *FnTy = | |||
1542 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); | |||
1543 | return CGM.CreateRuntimeFunction(FnTy, Name); | |||
1544 | } | |||
1545 | ||||
1546 | llvm::FunctionCallee | |||
1547 | CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) { | |||
1548 | assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1549, __extension__ __PRETTY_FUNCTION__)) | |||
1549 | "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1549, __extension__ __PRETTY_FUNCTION__)); | |||
1550 | StringRef Name = | |||
1551 | IVSize == 32 | |||
1552 | ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u") | |||
1553 | : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u"); | |||
1554 | llvm::Type *TypeParams[] = { | |||
1555 | getIdentTyPointerTy(), // loc | |||
1556 | CGM.Int32Ty, // tid | |||
1557 | }; | |||
1558 | auto *FnTy = | |||
1559 | llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); | |||
1560 | return CGM.CreateRuntimeFunction(FnTy, Name); | |||
1561 | } | |||
1562 | ||||
1563 | llvm::FunctionCallee | |||
1564 | CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) { | |||
1565 | assert((IVSize == 32 || IVSize == 64) &&(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1566, __extension__ __PRETTY_FUNCTION__)) | |||
1566 | "IV size is not compatible with the omp runtime")(static_cast <bool> ((IVSize == 32 || IVSize == 64) && "IV size is not compatible with the omp runtime") ? void (0) : __assert_fail ("(IVSize == 32 || IVSize == 64) && \"IV size is not compatible with the omp runtime\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1566, __extension__ __PRETTY_FUNCTION__)); | |||
1567 | StringRef Name = | |||
1568 | IVSize == 32 | |||
1569 | ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u") | |||
1570 | : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u"); | |||
1571 | llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; | |||
1572 | auto *PtrTy = llvm::PointerType::getUnqual(ITy); | |||
1573 | llvm::Type *TypeParams[] = { | |||
1574 | getIdentTyPointerTy(), // loc | |||
1575 | CGM.Int32Ty, // tid | |||
1576 | llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter | |||
1577 | PtrTy, // p_lower | |||
1578 | PtrTy, // p_upper | |||
1579 | PtrTy // p_stride | |||
1580 | }; | |||
1581 | auto *FnTy = | |||
1582 | llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); | |||
1583 | return CGM.CreateRuntimeFunction(FnTy, Name); | |||
1584 | } | |||
1585 | ||||
1586 | /// Obtain information that uniquely identifies a target entry. This | |||
1587 | /// consists of the file and device IDs as well as line number associated with | |||
1588 | /// the relevant entry source location. | |||
1589 | static llvm::TargetRegionEntryInfo | |||
1590 | getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc, | |||
1591 | StringRef ParentName = "") { | |||
1592 | SourceManager &SM = C.getSourceManager(); | |||
1593 | ||||
1594 | // The loc should be always valid and have a file ID (the user cannot use | |||
1595 | // #pragma directives in macros) | |||
1596 | ||||
1597 | assert(Loc.isValid() && "Source location is expected to be always valid.")(static_cast <bool> (Loc.isValid() && "Source location is expected to be always valid." ) ? void (0) : __assert_fail ("Loc.isValid() && \"Source location is expected to be always valid.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1597, __extension__ __PRETTY_FUNCTION__)); | |||
1598 | ||||
1599 | PresumedLoc PLoc = SM.getPresumedLoc(Loc); | |||
1600 | assert(PLoc.isValid() && "Source location is expected to be always valid.")(static_cast <bool> (PLoc.isValid() && "Source location is expected to be always valid." ) ? void (0) : __assert_fail ("PLoc.isValid() && \"Source location is expected to be always valid.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1600, __extension__ __PRETTY_FUNCTION__)); | |||
1601 | ||||
1602 | llvm::sys::fs::UniqueID ID; | |||
1603 | if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { | |||
1604 | PLoc = SM.getPresumedLoc(Loc, /*UseLineDirectives=*/false); | |||
1605 | assert(PLoc.isValid() && "Source location is expected to be always valid.")(static_cast <bool> (PLoc.isValid() && "Source location is expected to be always valid." ) ? void (0) : __assert_fail ("PLoc.isValid() && \"Source location is expected to be always valid.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1605, __extension__ __PRETTY_FUNCTION__)); | |||
1606 | if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) | |||
1607 | SM.getDiagnostics().Report(diag::err_cannot_open_file) | |||
1608 | << PLoc.getFilename() << EC.message(); | |||
1609 | } | |||
1610 | ||||
1611 | return llvm::TargetRegionEntryInfo(ParentName, ID.getDevice(), ID.getFile(), | |||
1612 | PLoc.getLine()); | |||
1613 | } | |||
1614 | ||||
1615 | Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) { | |||
1616 | if (CGM.getLangOpts().OpenMPSimd) | |||
1617 | return Address::invalid(); | |||
1618 | std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = | |||
1619 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); | |||
1620 | if (Res && (*Res == OMPDeclareTargetDeclAttr::MT_Link || | |||
1621 | ((*Res == OMPDeclareTargetDeclAttr::MT_To || | |||
1622 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && | |||
1623 | HasRequiresUnifiedSharedMemory))) { | |||
1624 | SmallString<64> PtrName; | |||
1625 | { | |||
1626 | llvm::raw_svector_ostream OS(PtrName); | |||
1627 | OS << CGM.getMangledName(GlobalDecl(VD)); | |||
1628 | if (!VD->isExternallyVisible()) { | |||
1629 | auto EntryInfo = getTargetEntryUniqueInfo( | |||
1630 | CGM.getContext(), VD->getCanonicalDecl()->getBeginLoc()); | |||
1631 | OS << llvm::format("_%x", EntryInfo.FileID); | |||
1632 | } | |||
1633 | OS << "_decl_tgt_ref_ptr"; | |||
1634 | } | |||
1635 | llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName); | |||
1636 | QualType PtrTy = CGM.getContext().getPointerType(VD->getType()); | |||
1637 | llvm::Type *LlvmPtrTy = CGM.getTypes().ConvertTypeForMem(PtrTy); | |||
1638 | if (!Ptr) { | |||
1639 | Ptr = OMPBuilder.getOrCreateInternalVariable(LlvmPtrTy, PtrName); | |||
1640 | ||||
1641 | auto *GV = cast<llvm::GlobalVariable>(Ptr); | |||
1642 | GV->setLinkage(llvm::GlobalValue::WeakAnyLinkage); | |||
1643 | ||||
1644 | if (!CGM.getLangOpts().OpenMPIsDevice) | |||
1645 | GV->setInitializer(CGM.GetAddrOfGlobal(VD)); | |||
1646 | registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr)); | |||
1647 | } | |||
1648 | return Address(Ptr, LlvmPtrTy, CGM.getContext().getDeclAlign(VD)); | |||
1649 | } | |||
1650 | return Address::invalid(); | |||
1651 | } | |||
1652 | ||||
1653 | llvm::Constant * | |||
1654 | CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) { | |||
1655 | assert(!CGM.getLangOpts().OpenMPUseTLS ||(static_cast <bool> (!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()) ? void ( 0) : __assert_fail ("!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1656, __extension__ __PRETTY_FUNCTION__)) | |||
1656 | !CGM.getContext().getTargetInfo().isTLSSupported())(static_cast <bool> (!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()) ? void ( 0) : __assert_fail ("!CGM.getLangOpts().OpenMPUseTLS || !CGM.getContext().getTargetInfo().isTLSSupported()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1656, __extension__ __PRETTY_FUNCTION__)); | |||
1657 | // Lookup the entry, lazily creating it if necessary. | |||
1658 | std::string Suffix = getName({"cache", ""}); | |||
1659 | return OMPBuilder.getOrCreateInternalVariable( | |||
1660 | CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix).str()); | |||
1661 | } | |||
1662 | ||||
1663 | Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF, | |||
1664 | const VarDecl *VD, | |||
1665 | Address VDAddr, | |||
1666 | SourceLocation Loc) { | |||
1667 | if (CGM.getLangOpts().OpenMPUseTLS && | |||
1668 | CGM.getContext().getTargetInfo().isTLSSupported()) | |||
1669 | return VDAddr; | |||
1670 | ||||
1671 | llvm::Type *VarTy = VDAddr.getElementType(); | |||
1672 | llvm::Value *Args[] = { | |||
1673 | emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
1674 | CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.Int8PtrTy), | |||
1675 | CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)), | |||
1676 | getOrCreateThreadPrivateCache(VD)}; | |||
1677 | return Address( | |||
1678 | CGF.EmitRuntimeCall( | |||
1679 | OMPBuilder.getOrCreateRuntimeFunction( | |||
1680 | CGM.getModule(), OMPRTL___kmpc_threadprivate_cached), | |||
1681 | Args), | |||
1682 | CGF.Int8Ty, VDAddr.getAlignment()); | |||
1683 | } | |||
1684 | ||||
1685 | void CGOpenMPRuntime::emitThreadPrivateVarInit( | |||
1686 | CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor, | |||
1687 | llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) { | |||
1688 | // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime | |||
1689 | // library. | |||
1690 | llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc); | |||
1691 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
1692 | CGM.getModule(), OMPRTL___kmpc_global_thread_num), | |||
1693 | OMPLoc); | |||
1694 | // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor) | |||
1695 | // to register constructor/destructor for variable. | |||
1696 | llvm::Value *Args[] = { | |||
1697 | OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy), | |||
1698 | Ctor, CopyCtor, Dtor}; | |||
1699 | CGF.EmitRuntimeCall( | |||
1700 | OMPBuilder.getOrCreateRuntimeFunction( | |||
1701 | CGM.getModule(), OMPRTL___kmpc_threadprivate_register), | |||
1702 | Args); | |||
1703 | } | |||
1704 | ||||
1705 | llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition( | |||
1706 | const VarDecl *VD, Address VDAddr, SourceLocation Loc, | |||
1707 | bool PerformInit, CodeGenFunction *CGF) { | |||
1708 | if (CGM.getLangOpts().OpenMPUseTLS && | |||
1709 | CGM.getContext().getTargetInfo().isTLSSupported()) | |||
1710 | return nullptr; | |||
1711 | ||||
1712 | VD = VD->getDefinition(CGM.getContext()); | |||
1713 | if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) { | |||
1714 | QualType ASTTy = VD->getType(); | |||
1715 | ||||
1716 | llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr; | |||
1717 | const Expr *Init = VD->getAnyInitializer(); | |||
1718 | if (CGM.getLangOpts().CPlusPlus && PerformInit) { | |||
1719 | // Generate function that re-emits the declaration's initializer into the | |||
1720 | // threadprivate copy of the variable VD | |||
1721 | CodeGenFunction CtorCGF(CGM); | |||
1722 | FunctionArgList Args; | |||
1723 | ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc, | |||
1724 | /*Id=*/nullptr, CGM.getContext().VoidPtrTy, | |||
1725 | ImplicitParamDecl::Other); | |||
1726 | Args.push_back(&Dst); | |||
1727 | ||||
1728 | const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( | |||
1729 | CGM.getContext().VoidPtrTy, Args); | |||
1730 | llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); | |||
1731 | std::string Name = getName({"__kmpc_global_ctor_", ""}); | |||
1732 | llvm::Function *Fn = | |||
1733 | CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc); | |||
1734 | CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI, | |||
1735 | Args, Loc, Loc); | |||
1736 | llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar( | |||
1737 | CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false, | |||
1738 | CGM.getContext().VoidPtrTy, Dst.getLocation()); | |||
1739 | Address Arg(ArgVal, CtorCGF.Int8Ty, VDAddr.getAlignment()); | |||
1740 | Arg = CtorCGF.Builder.CreateElementBitCast( | |||
1741 | Arg, CtorCGF.ConvertTypeForMem(ASTTy)); | |||
1742 | CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(), | |||
1743 | /*IsInitializer=*/true); | |||
1744 | ArgVal = CtorCGF.EmitLoadOfScalar( | |||
1745 | CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false, | |||
1746 | CGM.getContext().VoidPtrTy, Dst.getLocation()); | |||
1747 | CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue); | |||
1748 | CtorCGF.FinishFunction(); | |||
1749 | Ctor = Fn; | |||
1750 | } | |||
1751 | if (VD->getType().isDestructedType() != QualType::DK_none) { | |||
1752 | // Generate function that emits destructor call for the threadprivate copy | |||
1753 | // of the variable VD | |||
1754 | CodeGenFunction DtorCGF(CGM); | |||
1755 | FunctionArgList Args; | |||
1756 | ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc, | |||
1757 | /*Id=*/nullptr, CGM.getContext().VoidPtrTy, | |||
1758 | ImplicitParamDecl::Other); | |||
1759 | Args.push_back(&Dst); | |||
1760 | ||||
1761 | const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( | |||
1762 | CGM.getContext().VoidTy, Args); | |||
1763 | llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); | |||
1764 | std::string Name = getName({"__kmpc_global_dtor_", ""}); | |||
1765 | llvm::Function *Fn = | |||
1766 | CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc); | |||
1767 | auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF); | |||
1768 | DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args, | |||
1769 | Loc, Loc); | |||
1770 | // Create a scope with an artificial location for the body of this function. | |||
1771 | auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF); | |||
1772 | llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar( | |||
1773 | DtorCGF.GetAddrOfLocalVar(&Dst), | |||
1774 | /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation()); | |||
1775 | DtorCGF.emitDestroy( | |||
1776 | Address(ArgVal, DtorCGF.Int8Ty, VDAddr.getAlignment()), ASTTy, | |||
1777 | DtorCGF.getDestroyer(ASTTy.isDestructedType()), | |||
1778 | DtorCGF.needsEHCleanup(ASTTy.isDestructedType())); | |||
1779 | DtorCGF.FinishFunction(); | |||
1780 | Dtor = Fn; | |||
1781 | } | |||
1782 | // Do not emit init function if it is not required. | |||
1783 | if (!Ctor && !Dtor) | |||
1784 | return nullptr; | |||
1785 | ||||
1786 | llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; | |||
1787 | auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs, | |||
1788 | /*isVarArg=*/false) | |||
1789 | ->getPointerTo(); | |||
1790 | // Copying constructor for the threadprivate variable. | |||
1791 | // Must be NULL - reserved by runtime, but currently it requires that this | |||
1792 | // parameter is always NULL. Otherwise it fires assertion. | |||
1793 | CopyCtor = llvm::Constant::getNullValue(CopyCtorTy); | |||
1794 | if (Ctor == nullptr) { | |||
1795 | auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy, | |||
1796 | /*isVarArg=*/false) | |||
1797 | ->getPointerTo(); | |||
1798 | Ctor = llvm::Constant::getNullValue(CtorTy); | |||
1799 | } | |||
1800 | if (Dtor == nullptr) { | |||
1801 | auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, | |||
1802 | /*isVarArg=*/false) | |||
1803 | ->getPointerTo(); | |||
1804 | Dtor = llvm::Constant::getNullValue(DtorTy); | |||
1805 | } | |||
1806 | if (!CGF) { | |||
1807 | auto *InitFunctionTy = | |||
1808 | llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false); | |||
1809 | std::string Name = getName({"__omp_threadprivate_init_", ""}); | |||
1810 | llvm::Function *InitFunction = CGM.CreateGlobalInitOrCleanUpFunction( | |||
1811 | InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction()); | |||
1812 | CodeGenFunction InitCGF(CGM); | |||
1813 | FunctionArgList ArgList; | |||
1814 | InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction, | |||
1815 | CGM.getTypes().arrangeNullaryFunction(), ArgList, | |||
1816 | Loc, Loc); | |||
1817 | emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc); | |||
1818 | InitCGF.FinishFunction(); | |||
1819 | return InitFunction; | |||
1820 | } | |||
1821 | emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc); | |||
1822 | } | |||
1823 | return nullptr; | |||
1824 | } | |||
1825 | ||||
1826 | bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD, | |||
1827 | llvm::GlobalVariable *Addr, | |||
1828 | bool PerformInit) { | |||
1829 | if (CGM.getLangOpts().OMPTargetTriples.empty() && | |||
1830 | !CGM.getLangOpts().OpenMPIsDevice) | |||
1831 | return false; | |||
1832 | std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = | |||
1833 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); | |||
1834 | if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link || | |||
1835 | ((*Res == OMPDeclareTargetDeclAttr::MT_To || | |||
1836 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && | |||
1837 | HasRequiresUnifiedSharedMemory)) | |||
1838 | return CGM.getLangOpts().OpenMPIsDevice; | |||
1839 | VD = VD->getDefinition(CGM.getContext()); | |||
1840 | assert(VD && "Unknown VarDecl")(static_cast <bool> (VD && "Unknown VarDecl") ? void (0) : __assert_fail ("VD && \"Unknown VarDecl\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 1840, __extension__ __PRETTY_FUNCTION__)); | |||
1841 | ||||
1842 | if (!DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second) | |||
1843 | return CGM.getLangOpts().OpenMPIsDevice; | |||
1844 | ||||
1845 | QualType ASTTy = VD->getType(); | |||
1846 | SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc(); | |||
1847 | ||||
1848 | // Produce the unique prefix to identify the new target regions. We use | |||
1849 | // the source location of the variable declaration which we know to not | |||
1850 | // conflict with any target region. | |||
1851 | auto EntryInfo = | |||
1852 | getTargetEntryUniqueInfo(CGM.getContext(), Loc, VD->getName()); | |||
1853 | SmallString<128> Buffer, Out; | |||
1854 | OMPBuilder.OffloadInfoManager.getTargetRegionEntryFnName(Buffer, EntryInfo); | |||
1855 | ||||
1856 | const Expr *Init = VD->getAnyInitializer(); | |||
1857 | if (CGM.getLangOpts().CPlusPlus && PerformInit) { | |||
1858 | llvm::Constant *Ctor; | |||
1859 | llvm::Constant *ID; | |||
1860 | if (CGM.getLangOpts().OpenMPIsDevice) { | |||
1861 | // Generate function that re-emits the declaration's initializer into | |||
1862 | // the threadprivate copy of the variable VD | |||
1863 | CodeGenFunction CtorCGF(CGM); | |||
1864 | ||||
1865 | const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); | |||
1866 | llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); | |||
1867 | llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction( | |||
1868 | FTy, Twine(Buffer, "_ctor"), FI, Loc, false, | |||
1869 | llvm::GlobalValue::WeakODRLinkage); | |||
1870 | Fn->setVisibility(llvm::GlobalValue::ProtectedVisibility); | |||
1871 | if (CGM.getTriple().isAMDGCN()) | |||
1872 | Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL); | |||
1873 | auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF); | |||
1874 | CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, | |||
1875 | FunctionArgList(), Loc, Loc); | |||
1876 | auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF); | |||
1877 | llvm::Constant *AddrInAS0 = Addr; | |||
1878 | if (Addr->getAddressSpace() != 0) | |||
1879 | AddrInAS0 = llvm::ConstantExpr::getAddrSpaceCast( | |||
1880 | Addr, llvm::PointerType::getWithSamePointeeType( | |||
1881 | cast<llvm::PointerType>(Addr->getType()), 0)); | |||
1882 | CtorCGF.EmitAnyExprToMem(Init, | |||
1883 | Address(AddrInAS0, Addr->getValueType(), | |||
1884 | CGM.getContext().getDeclAlign(VD)), | |||
1885 | Init->getType().getQualifiers(), | |||
1886 | /*IsInitializer=*/true); | |||
1887 | CtorCGF.FinishFunction(); | |||
1888 | Ctor = Fn; | |||
1889 | ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); | |||
1890 | } else { | |||
1891 | Ctor = new llvm::GlobalVariable( | |||
1892 | CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, | |||
1893 | llvm::GlobalValue::PrivateLinkage, | |||
1894 | llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor")); | |||
1895 | ID = Ctor; | |||
1896 | } | |||
1897 | ||||
1898 | // Register the information for the entry associated with the constructor. | |||
1899 | Out.clear(); | |||
1900 | auto CtorEntryInfo = EntryInfo; | |||
1901 | CtorEntryInfo.ParentName = Twine(Buffer, "_ctor").toStringRef(Out); | |||
1902 | OMPBuilder.OffloadInfoManager.registerTargetRegionEntryInfo( | |||
1903 | CtorEntryInfo, Ctor, ID, | |||
1904 | llvm::OffloadEntriesInfoManager::OMPTargetRegionEntryCtor); | |||
1905 | } | |||
1906 | if (VD->getType().isDestructedType() != QualType::DK_none) { | |||
1907 | llvm::Constant *Dtor; | |||
1908 | llvm::Constant *ID; | |||
1909 | if (CGM.getLangOpts().OpenMPIsDevice) { | |||
1910 | // Generate function that emits destructor call for the threadprivate | |||
1911 | // copy of the variable VD | |||
1912 | CodeGenFunction DtorCGF(CGM); | |||
1913 | ||||
1914 | const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); | |||
1915 | llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); | |||
1916 | llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction( | |||
1917 | FTy, Twine(Buffer, "_dtor"), FI, Loc, false, | |||
1918 | llvm::GlobalValue::WeakODRLinkage); | |||
1919 | Fn->setVisibility(llvm::GlobalValue::ProtectedVisibility); | |||
1920 | if (CGM.getTriple().isAMDGCN()) | |||
1921 | Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL); | |||
1922 | auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF); | |||
1923 | DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, | |||
1924 | FunctionArgList(), Loc, Loc); | |||
1925 | // Create a scope with an artificial location for the body of this | |||
1926 | // function. | |||
1927 | auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF); | |||
1928 | llvm::Constant *AddrInAS0 = Addr; | |||
1929 | if (Addr->getAddressSpace() != 0) | |||
1930 | AddrInAS0 = llvm::ConstantExpr::getAddrSpaceCast( | |||
1931 | Addr, llvm::PointerType::getWithSamePointeeType( | |||
1932 | cast<llvm::PointerType>(Addr->getType()), 0)); | |||
1933 | DtorCGF.emitDestroy(Address(AddrInAS0, Addr->getValueType(), | |||
1934 | CGM.getContext().getDeclAlign(VD)), | |||
1935 | ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()), | |||
1936 | DtorCGF.needsEHCleanup(ASTTy.isDestructedType())); | |||
1937 | DtorCGF.FinishFunction(); | |||
1938 | Dtor = Fn; | |||
1939 | ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); | |||
1940 | } else { | |||
1941 | Dtor = new llvm::GlobalVariable( | |||
1942 | CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, | |||
1943 | llvm::GlobalValue::PrivateLinkage, | |||
1944 | llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor")); | |||
1945 | ID = Dtor; | |||
1946 | } | |||
1947 | // Register the information for the entry associated with the destructor. | |||
1948 | Out.clear(); | |||
1949 | auto DtorEntryInfo = EntryInfo; | |||
1950 | DtorEntryInfo.ParentName = Twine(Buffer, "_dtor").toStringRef(Out); | |||
1951 | OMPBuilder.OffloadInfoManager.registerTargetRegionEntryInfo( | |||
1952 | DtorEntryInfo, Dtor, ID, | |||
1953 | llvm::OffloadEntriesInfoManager::OMPTargetRegionEntryDtor); | |||
1954 | } | |||
1955 | return CGM.getLangOpts().OpenMPIsDevice; | |||
1956 | } | |||
1957 | ||||
1958 | Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, | |||
1959 | QualType VarType, | |||
1960 | StringRef Name) { | |||
1961 | std::string Suffix = getName({"artificial", ""}); | |||
1962 | llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType); | |||
1963 | llvm::GlobalVariable *GAddr = OMPBuilder.getOrCreateInternalVariable( | |||
1964 | VarLVType, Twine(Name).concat(Suffix).str()); | |||
1965 | if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPUseTLS && | |||
1966 | CGM.getTarget().isTLSSupported()) { | |||
1967 | GAddr->setThreadLocal(/*Val=*/true); | |||
1968 | return Address(GAddr, GAddr->getValueType(), | |||
1969 | CGM.getContext().getTypeAlignInChars(VarType)); | |||
1970 | } | |||
1971 | std::string CacheSuffix = getName({"cache", ""}); | |||
1972 | llvm::Value *Args[] = { | |||
1973 | emitUpdateLocation(CGF, SourceLocation()), | |||
1974 | getThreadID(CGF, SourceLocation()), | |||
1975 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy), | |||
1976 | CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy, | |||
1977 | /*isSigned=*/false), | |||
1978 | OMPBuilder.getOrCreateInternalVariable( | |||
1979 | CGM.VoidPtrPtrTy, | |||
1980 | Twine(Name).concat(Suffix).concat(CacheSuffix).str())}; | |||
1981 | return Address( | |||
1982 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
1983 | CGF.EmitRuntimeCall( | |||
1984 | OMPBuilder.getOrCreateRuntimeFunction( | |||
1985 | CGM.getModule(), OMPRTL___kmpc_threadprivate_cached), | |||
1986 | Args), | |||
1987 | VarLVType->getPointerTo(/*AddrSpace=*/0)), | |||
1988 | VarLVType, CGM.getContext().getTypeAlignInChars(VarType)); | |||
1989 | } | |||
1990 | ||||
1991 | void CGOpenMPRuntime::emitIfClause(CodeGenFunction &CGF, const Expr *Cond, | |||
1992 | const RegionCodeGenTy &ThenGen, | |||
1993 | const RegionCodeGenTy &ElseGen) { | |||
1994 | CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange()); | |||
1995 | ||||
1996 | // If the condition constant folds and can be elided, try to avoid emitting | |||
1997 | // the condition and the dead arm of the if/else. | |||
1998 | bool CondConstant; | |||
1999 | if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) { | |||
2000 | if (CondConstant) | |||
2001 | ThenGen(CGF); | |||
2002 | else | |||
2003 | ElseGen(CGF); | |||
2004 | return; | |||
2005 | } | |||
2006 | ||||
2007 | // Otherwise, the condition did not fold, or we couldn't elide it. Just | |||
2008 | // emit the conditional branch. | |||
2009 | llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then"); | |||
2010 | llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else"); | |||
2011 | llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end"); | |||
2012 | CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0); | |||
2013 | ||||
2014 | // Emit the 'then' code. | |||
2015 | CGF.EmitBlock(ThenBlock); | |||
2016 | ThenGen(CGF); | |||
2017 | CGF.EmitBranch(ContBlock); | |||
2018 | // Emit the 'else' code if present. | |||
2019 | // There is no need to emit line number for unconditional branch. | |||
2020 | (void)ApplyDebugLocation::CreateEmpty(CGF); | |||
2021 | CGF.EmitBlock(ElseBlock); | |||
2022 | ElseGen(CGF); | |||
2023 | // There is no need to emit line number for unconditional branch. | |||
2024 | (void)ApplyDebugLocation::CreateEmpty(CGF); | |||
2025 | CGF.EmitBranch(ContBlock); | |||
2026 | // Emit the continuation block for code after the if. | |||
2027 | CGF.EmitBlock(ContBlock, /*IsFinished=*/true); | |||
2028 | } | |||
2029 | ||||
2030 | void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
2031 | llvm::Function *OutlinedFn, | |||
2032 | ArrayRef<llvm::Value *> CapturedVars, | |||
2033 | const Expr *IfCond, | |||
2034 | llvm::Value *NumThreads) { | |||
2035 | if (!CGF.HaveInsertPoint()) | |||
2036 | return; | |||
2037 | llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc); | |||
2038 | auto &M = CGM.getModule(); | |||
2039 | auto &&ThenGen = [&M, OutlinedFn, CapturedVars, RTLoc, | |||
2040 | this](CodeGenFunction &CGF, PrePostActionTy &) { | |||
2041 | // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn); | |||
2042 | CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); | |||
2043 | llvm::Value *Args[] = { | |||
2044 | RTLoc, | |||
2045 | CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars | |||
2046 | CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())}; | |||
2047 | llvm::SmallVector<llvm::Value *, 16> RealArgs; | |||
2048 | RealArgs.append(std::begin(Args), std::end(Args)); | |||
2049 | RealArgs.append(CapturedVars.begin(), CapturedVars.end()); | |||
2050 | ||||
2051 | llvm::FunctionCallee RTLFn = | |||
2052 | OMPBuilder.getOrCreateRuntimeFunction(M, OMPRTL___kmpc_fork_call); | |||
2053 | CGF.EmitRuntimeCall(RTLFn, RealArgs); | |||
2054 | }; | |||
2055 | auto &&ElseGen = [&M, OutlinedFn, CapturedVars, RTLoc, Loc, | |||
2056 | this](CodeGenFunction &CGF, PrePostActionTy &) { | |||
2057 | CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); | |||
2058 | llvm::Value *ThreadID = RT.getThreadID(CGF, Loc); | |||
2059 | // Build calls: | |||
2060 | // __kmpc_serialized_parallel(&Loc, GTid); | |||
2061 | llvm::Value *Args[] = {RTLoc, ThreadID}; | |||
2062 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2063 | M, OMPRTL___kmpc_serialized_parallel), | |||
2064 | Args); | |||
2065 | ||||
2066 | // OutlinedFn(>id, &zero_bound, CapturedStruct); | |||
2067 | Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc); | |||
2068 | Address ZeroAddrBound = | |||
2069 | CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty, | |||
2070 | /*Name=*/".bound.zero.addr"); | |||
2071 | CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddrBound); | |||
2072 | llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; | |||
2073 | // ThreadId for serialized parallels is 0. | |||
2074 | OutlinedFnArgs.push_back(ThreadIDAddr.getPointer()); | |||
2075 | OutlinedFnArgs.push_back(ZeroAddrBound.getPointer()); | |||
2076 | OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); | |||
2077 | ||||
2078 | // Ensure we do not inline the function. This is trivially true for the ones | |||
2079 | // passed to __kmpc_fork_call but the ones called in serialized regions | |||
2080 | // could be inlined. This is not a perfect but it is closer to the invariant | |||
2081 | // we want, namely, every data environment starts with a new function. | |||
2082 | // TODO: We should pass the if condition to the runtime function and do the | |||
2083 | // handling there. Much cleaner code. | |||
2084 | OutlinedFn->removeFnAttr(llvm::Attribute::AlwaysInline); | |||
2085 | OutlinedFn->addFnAttr(llvm::Attribute::NoInline); | |||
2086 | RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs); | |||
2087 | ||||
2088 | // __kmpc_end_serialized_parallel(&Loc, GTid); | |||
2089 | llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID}; | |||
2090 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2091 | M, OMPRTL___kmpc_end_serialized_parallel), | |||
2092 | EndArgs); | |||
2093 | }; | |||
2094 | if (IfCond) { | |||
2095 | emitIfClause(CGF, IfCond, ThenGen, ElseGen); | |||
2096 | } else { | |||
2097 | RegionCodeGenTy ThenRCG(ThenGen); | |||
2098 | ThenRCG(CGF); | |||
2099 | } | |||
2100 | } | |||
2101 | ||||
2102 | // If we're inside an (outlined) parallel region, use the region info's | |||
2103 | // thread-ID variable (it is passed in a first argument of the outlined function | |||
2104 | // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in | |||
2105 | // regular serial code region, get thread ID by calling kmp_int32 | |||
2106 | // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and | |||
2107 | // return the address of that temp. | |||
2108 | Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF, | |||
2109 | SourceLocation Loc) { | |||
2110 | if (auto *OMPRegionInfo = | |||
2111 | dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) | |||
2112 | if (OMPRegionInfo->getThreadIDVariable()) | |||
2113 | return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress(CGF); | |||
2114 | ||||
2115 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
2116 | QualType Int32Ty = | |||
2117 | CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true); | |||
2118 | Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp."); | |||
2119 | CGF.EmitStoreOfScalar(ThreadID, | |||
2120 | CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty)); | |||
2121 | ||||
2122 | return ThreadIDTemp; | |||
2123 | } | |||
2124 | ||||
2125 | llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) { | |||
2126 | std::string Prefix = Twine("gomp_critical_user_", CriticalName).str(); | |||
2127 | std::string Name = getName({Prefix, "var"}); | |||
2128 | return OMPBuilder.getOrCreateInternalVariable(KmpCriticalNameTy, Name); | |||
2129 | } | |||
2130 | ||||
2131 | namespace { | |||
2132 | /// Common pre(post)-action for different OpenMP constructs. | |||
2133 | class CommonActionTy final : public PrePostActionTy { | |||
2134 | llvm::FunctionCallee EnterCallee; | |||
2135 | ArrayRef<llvm::Value *> EnterArgs; | |||
2136 | llvm::FunctionCallee ExitCallee; | |||
2137 | ArrayRef<llvm::Value *> ExitArgs; | |||
2138 | bool Conditional; | |||
2139 | llvm::BasicBlock *ContBlock = nullptr; | |||
2140 | ||||
2141 | public: | |||
2142 | CommonActionTy(llvm::FunctionCallee EnterCallee, | |||
2143 | ArrayRef<llvm::Value *> EnterArgs, | |||
2144 | llvm::FunctionCallee ExitCallee, | |||
2145 | ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false) | |||
2146 | : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee), | |||
2147 | ExitArgs(ExitArgs), Conditional(Conditional) {} | |||
2148 | void Enter(CodeGenFunction &CGF) override { | |||
2149 | llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs); | |||
2150 | if (Conditional) { | |||
2151 | llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes); | |||
2152 | auto *ThenBlock = CGF.createBasicBlock("omp_if.then"); | |||
2153 | ContBlock = CGF.createBasicBlock("omp_if.end"); | |||
2154 | // Generate the branch (If-stmt) | |||
2155 | CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock); | |||
2156 | CGF.EmitBlock(ThenBlock); | |||
2157 | } | |||
2158 | } | |||
2159 | void Done(CodeGenFunction &CGF) { | |||
2160 | // Emit the rest of blocks/branches | |||
2161 | CGF.EmitBranch(ContBlock); | |||
2162 | CGF.EmitBlock(ContBlock, true); | |||
2163 | } | |||
2164 | void Exit(CodeGenFunction &CGF) override { | |||
2165 | CGF.EmitRuntimeCall(ExitCallee, ExitArgs); | |||
2166 | } | |||
2167 | }; | |||
2168 | } // anonymous namespace | |||
2169 | ||||
2170 | void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF, | |||
2171 | StringRef CriticalName, | |||
2172 | const RegionCodeGenTy &CriticalOpGen, | |||
2173 | SourceLocation Loc, const Expr *Hint) { | |||
2174 | // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]); | |||
2175 | // CriticalOpGen(); | |||
2176 | // __kmpc_end_critical(ident_t *, gtid, Lock); | |||
2177 | // Prepare arguments and build a call to __kmpc_critical | |||
2178 | if (!CGF.HaveInsertPoint()) | |||
2179 | return; | |||
2180 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2181 | getCriticalRegionLock(CriticalName)}; | |||
2182 | llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), | |||
2183 | std::end(Args)); | |||
2184 | if (Hint
| |||
2185 | EnterArgs.push_back(CGF.Builder.CreateIntCast( | |||
2186 | CGF.EmitScalarExpr(Hint), CGM.Int32Ty, /*isSigned=*/false)); | |||
2187 | } | |||
2188 | CommonActionTy Action( | |||
2189 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2190 | CGM.getModule(), | |||
2191 | Hint
| |||
2192 | EnterArgs, | |||
2193 | OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), | |||
2194 | OMPRTL___kmpc_end_critical), | |||
2195 | Args); | |||
2196 | CriticalOpGen.setAction(Action); | |||
2197 | emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen); | |||
| ||||
2198 | } | |||
2199 | ||||
2200 | void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF, | |||
2201 | const RegionCodeGenTy &MasterOpGen, | |||
2202 | SourceLocation Loc) { | |||
2203 | if (!CGF.HaveInsertPoint()) | |||
2204 | return; | |||
2205 | // if(__kmpc_master(ident_t *, gtid)) { | |||
2206 | // MasterOpGen(); | |||
2207 | // __kmpc_end_master(ident_t *, gtid); | |||
2208 | // } | |||
2209 | // Prepare arguments and build a call to __kmpc_master | |||
2210 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2211 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2212 | CGM.getModule(), OMPRTL___kmpc_master), | |||
2213 | Args, | |||
2214 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2215 | CGM.getModule(), OMPRTL___kmpc_end_master), | |||
2216 | Args, | |||
2217 | /*Conditional=*/true); | |||
2218 | MasterOpGen.setAction(Action); | |||
2219 | emitInlinedDirective(CGF, OMPD_master, MasterOpGen); | |||
2220 | Action.Done(CGF); | |||
2221 | } | |||
2222 | ||||
2223 | void CGOpenMPRuntime::emitMaskedRegion(CodeGenFunction &CGF, | |||
2224 | const RegionCodeGenTy &MaskedOpGen, | |||
2225 | SourceLocation Loc, const Expr *Filter) { | |||
2226 | if (!CGF.HaveInsertPoint()) | |||
2227 | return; | |||
2228 | // if(__kmpc_masked(ident_t *, gtid, filter)) { | |||
2229 | // MaskedOpGen(); | |||
2230 | // __kmpc_end_masked(iden_t *, gtid); | |||
2231 | // } | |||
2232 | // Prepare arguments and build a call to __kmpc_masked | |||
2233 | llvm::Value *FilterVal = Filter | |||
2234 | ? CGF.EmitScalarExpr(Filter, CGF.Int32Ty) | |||
2235 | : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0); | |||
2236 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2237 | FilterVal}; | |||
2238 | llvm::Value *ArgsEnd[] = {emitUpdateLocation(CGF, Loc), | |||
2239 | getThreadID(CGF, Loc)}; | |||
2240 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2241 | CGM.getModule(), OMPRTL___kmpc_masked), | |||
2242 | Args, | |||
2243 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2244 | CGM.getModule(), OMPRTL___kmpc_end_masked), | |||
2245 | ArgsEnd, | |||
2246 | /*Conditional=*/true); | |||
2247 | MaskedOpGen.setAction(Action); | |||
2248 | emitInlinedDirective(CGF, OMPD_masked, MaskedOpGen); | |||
2249 | Action.Done(CGF); | |||
2250 | } | |||
2251 | ||||
2252 | void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF, | |||
2253 | SourceLocation Loc) { | |||
2254 | if (!CGF.HaveInsertPoint()) | |||
2255 | return; | |||
2256 | if (CGF.CGM.getLangOpts().OpenMPIRBuilder) { | |||
2257 | OMPBuilder.createTaskyield(CGF.Builder); | |||
2258 | } else { | |||
2259 | // Build call __kmpc_omp_taskyield(loc, thread_id, 0); | |||
2260 | llvm::Value *Args[] = { | |||
2261 | emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2262 | llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)}; | |||
2263 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2264 | CGM.getModule(), OMPRTL___kmpc_omp_taskyield), | |||
2265 | Args); | |||
2266 | } | |||
2267 | ||||
2268 | if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) | |||
2269 | Region->emitUntiedSwitch(CGF); | |||
2270 | } | |||
2271 | ||||
2272 | void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF, | |||
2273 | const RegionCodeGenTy &TaskgroupOpGen, | |||
2274 | SourceLocation Loc) { | |||
2275 | if (!CGF.HaveInsertPoint()) | |||
2276 | return; | |||
2277 | // __kmpc_taskgroup(ident_t *, gtid); | |||
2278 | // TaskgroupOpGen(); | |||
2279 | // __kmpc_end_taskgroup(ident_t *, gtid); | |||
2280 | // Prepare arguments and build a call to __kmpc_taskgroup | |||
2281 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2282 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2283 | CGM.getModule(), OMPRTL___kmpc_taskgroup), | |||
2284 | Args, | |||
2285 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2286 | CGM.getModule(), OMPRTL___kmpc_end_taskgroup), | |||
2287 | Args); | |||
2288 | TaskgroupOpGen.setAction(Action); | |||
2289 | emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen); | |||
2290 | } | |||
2291 | ||||
2292 | /// Given an array of pointers to variables, project the address of a | |||
2293 | /// given variable. | |||
2294 | static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array, | |||
2295 | unsigned Index, const VarDecl *Var) { | |||
2296 | // Pull out the pointer to the variable. | |||
2297 | Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index); | |||
2298 | llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr); | |||
2299 | ||||
2300 | llvm::Type *ElemTy = CGF.ConvertTypeForMem(Var->getType()); | |||
2301 | return Address( | |||
2302 | CGF.Builder.CreateBitCast( | |||
2303 | Ptr, ElemTy->getPointerTo(Ptr->getType()->getPointerAddressSpace())), | |||
2304 | ElemTy, CGF.getContext().getDeclAlign(Var)); | |||
2305 | } | |||
2306 | ||||
2307 | static llvm::Value *emitCopyprivateCopyFunction( | |||
2308 | CodeGenModule &CGM, llvm::Type *ArgsElemType, | |||
2309 | ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, | |||
2310 | ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps, | |||
2311 | SourceLocation Loc) { | |||
2312 | ASTContext &C = CGM.getContext(); | |||
2313 | // void copy_func(void *LHSArg, void *RHSArg); | |||
2314 | FunctionArgList Args; | |||
2315 | ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
2316 | ImplicitParamDecl::Other); | |||
2317 | ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
2318 | ImplicitParamDecl::Other); | |||
2319 | Args.push_back(&LHSArg); | |||
2320 | Args.push_back(&RHSArg); | |||
2321 | const auto &CGFI = | |||
2322 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
2323 | std::string Name = | |||
2324 | CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"}); | |||
2325 | auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI), | |||
2326 | llvm::GlobalValue::InternalLinkage, Name, | |||
2327 | &CGM.getModule()); | |||
2328 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); | |||
2329 | Fn->setDoesNotRecurse(); | |||
2330 | CodeGenFunction CGF(CGM); | |||
2331 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); | |||
2332 | // Dest = (void*[n])(LHSArg); | |||
2333 | // Src = (void*[n])(RHSArg); | |||
2334 | Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
2335 | CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)), | |||
2336 | ArgsElemType->getPointerTo()), | |||
2337 | ArgsElemType, CGF.getPointerAlign()); | |||
2338 | Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
2339 | CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)), | |||
2340 | ArgsElemType->getPointerTo()), | |||
2341 | ArgsElemType, CGF.getPointerAlign()); | |||
2342 | // *(Type0*)Dst[0] = *(Type0*)Src[0]; | |||
2343 | // *(Type1*)Dst[1] = *(Type1*)Src[1]; | |||
2344 | // ... | |||
2345 | // *(Typen*)Dst[n] = *(Typen*)Src[n]; | |||
2346 | for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) { | |||
2347 | const auto *DestVar = | |||
2348 | cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()); | |||
2349 | Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar); | |||
2350 | ||||
2351 | const auto *SrcVar = | |||
2352 | cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()); | |||
2353 | Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar); | |||
2354 | ||||
2355 | const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl(); | |||
2356 | QualType Type = VD->getType(); | |||
2357 | CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]); | |||
2358 | } | |||
2359 | CGF.FinishFunction(); | |||
2360 | return Fn; | |||
2361 | } | |||
2362 | ||||
2363 | void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF, | |||
2364 | const RegionCodeGenTy &SingleOpGen, | |||
2365 | SourceLocation Loc, | |||
2366 | ArrayRef<const Expr *> CopyprivateVars, | |||
2367 | ArrayRef<const Expr *> SrcExprs, | |||
2368 | ArrayRef<const Expr *> DstExprs, | |||
2369 | ArrayRef<const Expr *> AssignmentOps) { | |||
2370 | if (!CGF.HaveInsertPoint()) | |||
2371 | return; | |||
2372 | assert(CopyprivateVars.size() == SrcExprs.size() &&(static_cast <bool> (CopyprivateVars.size() == SrcExprs .size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()) ? void (0) : __assert_fail ("CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2374, __extension__ __PRETTY_FUNCTION__)) | |||
2373 | CopyprivateVars.size() == DstExprs.size() &&(static_cast <bool> (CopyprivateVars.size() == SrcExprs .size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()) ? void (0) : __assert_fail ("CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2374, __extension__ __PRETTY_FUNCTION__)) | |||
2374 | CopyprivateVars.size() == AssignmentOps.size())(static_cast <bool> (CopyprivateVars.size() == SrcExprs .size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()) ? void (0) : __assert_fail ("CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == DstExprs.size() && CopyprivateVars.size() == AssignmentOps.size()" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2374, __extension__ __PRETTY_FUNCTION__)); | |||
2375 | ASTContext &C = CGM.getContext(); | |||
2376 | // int32 did_it = 0; | |||
2377 | // if(__kmpc_single(ident_t *, gtid)) { | |||
2378 | // SingleOpGen(); | |||
2379 | // __kmpc_end_single(ident_t *, gtid); | |||
2380 | // did_it = 1; | |||
2381 | // } | |||
2382 | // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>, | |||
2383 | // <copy_func>, did_it); | |||
2384 | ||||
2385 | Address DidIt = Address::invalid(); | |||
2386 | if (!CopyprivateVars.empty()) { | |||
2387 | // int32 did_it = 0; | |||
2388 | QualType KmpInt32Ty = | |||
2389 | C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); | |||
2390 | DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it"); | |||
2391 | CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt); | |||
2392 | } | |||
2393 | // Prepare arguments and build a call to __kmpc_single | |||
2394 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2395 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2396 | CGM.getModule(), OMPRTL___kmpc_single), | |||
2397 | Args, | |||
2398 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2399 | CGM.getModule(), OMPRTL___kmpc_end_single), | |||
2400 | Args, | |||
2401 | /*Conditional=*/true); | |||
2402 | SingleOpGen.setAction(Action); | |||
2403 | emitInlinedDirective(CGF, OMPD_single, SingleOpGen); | |||
2404 | if (DidIt.isValid()) { | |||
2405 | // did_it = 1; | |||
2406 | CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt); | |||
2407 | } | |||
2408 | Action.Done(CGF); | |||
2409 | // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>, | |||
2410 | // <copy_func>, did_it); | |||
2411 | if (DidIt.isValid()) { | |||
2412 | llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size()); | |||
2413 | QualType CopyprivateArrayTy = C.getConstantArrayType( | |||
2414 | C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal, | |||
2415 | /*IndexTypeQuals=*/0); | |||
2416 | // Create a list of all private variables for copyprivate. | |||
2417 | Address CopyprivateList = | |||
2418 | CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list"); | |||
2419 | for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) { | |||
2420 | Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I); | |||
2421 | CGF.Builder.CreateStore( | |||
2422 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
2423 | CGF.EmitLValue(CopyprivateVars[I]).getPointer(CGF), | |||
2424 | CGF.VoidPtrTy), | |||
2425 | Elem); | |||
2426 | } | |||
2427 | // Build function that copies private values from single region to all other | |||
2428 | // threads in the corresponding parallel region. | |||
2429 | llvm::Value *CpyFn = emitCopyprivateCopyFunction( | |||
2430 | CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy), CopyprivateVars, | |||
2431 | SrcExprs, DstExprs, AssignmentOps, Loc); | |||
2432 | llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy); | |||
2433 | Address CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
2434 | CopyprivateList, CGF.VoidPtrTy, CGF.Int8Ty); | |||
2435 | llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt); | |||
2436 | llvm::Value *Args[] = { | |||
2437 | emitUpdateLocation(CGF, Loc), // ident_t *<loc> | |||
2438 | getThreadID(CGF, Loc), // i32 <gtid> | |||
2439 | BufSize, // size_t <buf_size> | |||
2440 | CL.getPointer(), // void *<copyprivate list> | |||
2441 | CpyFn, // void (*) (void *, void *) <copy_func> | |||
2442 | DidItVal // i32 did_it | |||
2443 | }; | |||
2444 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2445 | CGM.getModule(), OMPRTL___kmpc_copyprivate), | |||
2446 | Args); | |||
2447 | } | |||
2448 | } | |||
2449 | ||||
2450 | void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF, | |||
2451 | const RegionCodeGenTy &OrderedOpGen, | |||
2452 | SourceLocation Loc, bool IsThreads) { | |||
2453 | if (!CGF.HaveInsertPoint()) | |||
2454 | return; | |||
2455 | // __kmpc_ordered(ident_t *, gtid); | |||
2456 | // OrderedOpGen(); | |||
2457 | // __kmpc_end_ordered(ident_t *, gtid); | |||
2458 | // Prepare arguments and build a call to __kmpc_ordered | |||
2459 | if (IsThreads) { | |||
2460 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2461 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
2462 | CGM.getModule(), OMPRTL___kmpc_ordered), | |||
2463 | Args, | |||
2464 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2465 | CGM.getModule(), OMPRTL___kmpc_end_ordered), | |||
2466 | Args); | |||
2467 | OrderedOpGen.setAction(Action); | |||
2468 | emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen); | |||
2469 | return; | |||
2470 | } | |||
2471 | emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen); | |||
2472 | } | |||
2473 | ||||
2474 | unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) { | |||
2475 | unsigned Flags; | |||
2476 | if (Kind == OMPD_for) | |||
2477 | Flags = OMP_IDENT_BARRIER_IMPL_FOR; | |||
2478 | else if (Kind == OMPD_sections) | |||
2479 | Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS; | |||
2480 | else if (Kind == OMPD_single) | |||
2481 | Flags = OMP_IDENT_BARRIER_IMPL_SINGLE; | |||
2482 | else if (Kind == OMPD_barrier) | |||
2483 | Flags = OMP_IDENT_BARRIER_EXPL; | |||
2484 | else | |||
2485 | Flags = OMP_IDENT_BARRIER_IMPL; | |||
2486 | return Flags; | |||
2487 | } | |||
2488 | ||||
2489 | void CGOpenMPRuntime::getDefaultScheduleAndChunk( | |||
2490 | CodeGenFunction &CGF, const OMPLoopDirective &S, | |||
2491 | OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const { | |||
2492 | // Check if the loop directive is actually a doacross loop directive. In this | |||
2493 | // case choose static, 1 schedule. | |||
2494 | if (llvm::any_of( | |||
2495 | S.getClausesOfKind<OMPOrderedClause>(), | |||
2496 | [](const OMPOrderedClause *C) { return C->getNumForLoops(); })) { | |||
2497 | ScheduleKind = OMPC_SCHEDULE_static; | |||
2498 | // Chunk size is 1 in this case. | |||
2499 | llvm::APInt ChunkSize(32, 1); | |||
2500 | ChunkExpr = IntegerLiteral::Create( | |||
2501 | CGF.getContext(), ChunkSize, | |||
2502 | CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0), | |||
2503 | SourceLocation()); | |||
2504 | } | |||
2505 | } | |||
2506 | ||||
2507 | void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
2508 | OpenMPDirectiveKind Kind, bool EmitChecks, | |||
2509 | bool ForceSimpleCall) { | |||
2510 | // Check if we should use the OMPBuilder | |||
2511 | auto *OMPRegionInfo = | |||
2512 | dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo); | |||
2513 | if (CGF.CGM.getLangOpts().OpenMPIRBuilder) { | |||
2514 | CGF.Builder.restoreIP(OMPBuilder.createBarrier( | |||
2515 | CGF.Builder, Kind, ForceSimpleCall, EmitChecks)); | |||
2516 | return; | |||
2517 | } | |||
2518 | ||||
2519 | if (!CGF.HaveInsertPoint()) | |||
2520 | return; | |||
2521 | // Build call __kmpc_cancel_barrier(loc, thread_id); | |||
2522 | // Build call __kmpc_barrier(loc, thread_id); | |||
2523 | unsigned Flags = getDefaultFlagsForBarriers(Kind); | |||
2524 | // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc, | |||
2525 | // thread_id); | |||
2526 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags), | |||
2527 | getThreadID(CGF, Loc)}; | |||
2528 | if (OMPRegionInfo) { | |||
2529 | if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) { | |||
2530 | llvm::Value *Result = CGF.EmitRuntimeCall( | |||
2531 | OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), | |||
2532 | OMPRTL___kmpc_cancel_barrier), | |||
2533 | Args); | |||
2534 | if (EmitChecks) { | |||
2535 | // if (__kmpc_cancel_barrier()) { | |||
2536 | // exit from construct; | |||
2537 | // } | |||
2538 | llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit"); | |||
2539 | llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue"); | |||
2540 | llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result); | |||
2541 | CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB); | |||
2542 | CGF.EmitBlock(ExitBB); | |||
2543 | // exit from construct; | |||
2544 | CodeGenFunction::JumpDest CancelDestination = | |||
2545 | CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind()); | |||
2546 | CGF.EmitBranchThroughCleanup(CancelDestination); | |||
2547 | CGF.EmitBlock(ContBB, /*IsFinished=*/true); | |||
2548 | } | |||
2549 | return; | |||
2550 | } | |||
2551 | } | |||
2552 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2553 | CGM.getModule(), OMPRTL___kmpc_barrier), | |||
2554 | Args); | |||
2555 | } | |||
2556 | ||||
2557 | void CGOpenMPRuntime::emitErrorCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
2558 | Expr *ME, bool IsFatal) { | |||
2559 | llvm::Value *MVL = | |||
2560 | ME ? CGF.EmitStringLiteralLValue(cast<StringLiteral>(ME)).getPointer(CGF) | |||
2561 | : llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
2562 | // Build call void __kmpc_error(ident_t *loc, int severity, const char | |||
2563 | // *message) | |||
2564 | llvm::Value *Args[] = { | |||
2565 | emitUpdateLocation(CGF, Loc, /*Flags=*/0, /*GenLoc=*/true), | |||
2566 | llvm::ConstantInt::get(CGM.Int32Ty, IsFatal ? 2 : 1), | |||
2567 | CGF.Builder.CreatePointerCast(MVL, CGM.Int8PtrTy)}; | |||
2568 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2569 | CGM.getModule(), OMPRTL___kmpc_error), | |||
2570 | Args); | |||
2571 | } | |||
2572 | ||||
2573 | /// Map the OpenMP loop schedule to the runtime enumeration. | |||
2574 | static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind, | |||
2575 | bool Chunked, bool Ordered) { | |||
2576 | switch (ScheduleKind) { | |||
2577 | case OMPC_SCHEDULE_static: | |||
2578 | return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked) | |||
2579 | : (Ordered ? OMP_ord_static : OMP_sch_static); | |||
2580 | case OMPC_SCHEDULE_dynamic: | |||
2581 | return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked; | |||
2582 | case OMPC_SCHEDULE_guided: | |||
2583 | return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked; | |||
2584 | case OMPC_SCHEDULE_runtime: | |||
2585 | return Ordered ? OMP_ord_runtime : OMP_sch_runtime; | |||
2586 | case OMPC_SCHEDULE_auto: | |||
2587 | return Ordered ? OMP_ord_auto : OMP_sch_auto; | |||
2588 | case OMPC_SCHEDULE_unknown: | |||
2589 | assert(!Chunked && "chunk was specified but schedule kind not known")(static_cast <bool> (!Chunked && "chunk was specified but schedule kind not known" ) ? void (0) : __assert_fail ("!Chunked && \"chunk was specified but schedule kind not known\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2589, __extension__ __PRETTY_FUNCTION__)); | |||
2590 | return Ordered ? OMP_ord_static : OMP_sch_static; | |||
2591 | } | |||
2592 | llvm_unreachable("Unexpected runtime schedule")::llvm::llvm_unreachable_internal("Unexpected runtime schedule" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2592); | |||
2593 | } | |||
2594 | ||||
2595 | /// Map the OpenMP distribute schedule to the runtime enumeration. | |||
2596 | static OpenMPSchedType | |||
2597 | getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) { | |||
2598 | // only static is allowed for dist_schedule | |||
2599 | return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static; | |||
2600 | } | |||
2601 | ||||
2602 | bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, | |||
2603 | bool Chunked) const { | |||
2604 | OpenMPSchedType Schedule = | |||
2605 | getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false); | |||
2606 | return Schedule == OMP_sch_static; | |||
2607 | } | |||
2608 | ||||
2609 | bool CGOpenMPRuntime::isStaticNonchunked( | |||
2610 | OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const { | |||
2611 | OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked); | |||
2612 | return Schedule == OMP_dist_sch_static; | |||
2613 | } | |||
2614 | ||||
2615 | bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, | |||
2616 | bool Chunked) const { | |||
2617 | OpenMPSchedType Schedule = | |||
2618 | getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false); | |||
2619 | return Schedule == OMP_sch_static_chunked; | |||
2620 | } | |||
2621 | ||||
2622 | bool CGOpenMPRuntime::isStaticChunked( | |||
2623 | OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const { | |||
2624 | OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked); | |||
2625 | return Schedule == OMP_dist_sch_static_chunked; | |||
2626 | } | |||
2627 | ||||
2628 | bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const { | |||
2629 | OpenMPSchedType Schedule = | |||
2630 | getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false); | |||
2631 | assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here")(static_cast <bool> (Schedule != OMP_sch_static_chunked && "cannot be chunked here") ? void (0) : __assert_fail ("Schedule != OMP_sch_static_chunked && \"cannot be chunked here\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2631, __extension__ __PRETTY_FUNCTION__)); | |||
2632 | return Schedule != OMP_sch_static; | |||
2633 | } | |||
2634 | ||||
2635 | static int addMonoNonMonoModifier(CodeGenModule &CGM, OpenMPSchedType Schedule, | |||
2636 | OpenMPScheduleClauseModifier M1, | |||
2637 | OpenMPScheduleClauseModifier M2) { | |||
2638 | int Modifier = 0; | |||
2639 | switch (M1) { | |||
2640 | case OMPC_SCHEDULE_MODIFIER_monotonic: | |||
2641 | Modifier = OMP_sch_modifier_monotonic; | |||
2642 | break; | |||
2643 | case OMPC_SCHEDULE_MODIFIER_nonmonotonic: | |||
2644 | Modifier = OMP_sch_modifier_nonmonotonic; | |||
2645 | break; | |||
2646 | case OMPC_SCHEDULE_MODIFIER_simd: | |||
2647 | if (Schedule == OMP_sch_static_chunked) | |||
2648 | Schedule = OMP_sch_static_balanced_chunked; | |||
2649 | break; | |||
2650 | case OMPC_SCHEDULE_MODIFIER_last: | |||
2651 | case OMPC_SCHEDULE_MODIFIER_unknown: | |||
2652 | break; | |||
2653 | } | |||
2654 | switch (M2) { | |||
2655 | case OMPC_SCHEDULE_MODIFIER_monotonic: | |||
2656 | Modifier = OMP_sch_modifier_monotonic; | |||
2657 | break; | |||
2658 | case OMPC_SCHEDULE_MODIFIER_nonmonotonic: | |||
2659 | Modifier = OMP_sch_modifier_nonmonotonic; | |||
2660 | break; | |||
2661 | case OMPC_SCHEDULE_MODIFIER_simd: | |||
2662 | if (Schedule == OMP_sch_static_chunked) | |||
2663 | Schedule = OMP_sch_static_balanced_chunked; | |||
2664 | break; | |||
2665 | case OMPC_SCHEDULE_MODIFIER_last: | |||
2666 | case OMPC_SCHEDULE_MODIFIER_unknown: | |||
2667 | break; | |||
2668 | } | |||
2669 | // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Desription. | |||
2670 | // If the static schedule kind is specified or if the ordered clause is | |||
2671 | // specified, and if the nonmonotonic modifier is not specified, the effect is | |||
2672 | // as if the monotonic modifier is specified. Otherwise, unless the monotonic | |||
2673 | // modifier is specified, the effect is as if the nonmonotonic modifier is | |||
2674 | // specified. | |||
2675 | if (CGM.getLangOpts().OpenMP >= 50 && Modifier == 0) { | |||
2676 | if (!(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static || | |||
2677 | Schedule == OMP_sch_static_balanced_chunked || | |||
2678 | Schedule == OMP_ord_static_chunked || Schedule == OMP_ord_static || | |||
2679 | Schedule == OMP_dist_sch_static_chunked || | |||
2680 | Schedule == OMP_dist_sch_static)) | |||
2681 | Modifier = OMP_sch_modifier_nonmonotonic; | |||
2682 | } | |||
2683 | return Schedule | Modifier; | |||
2684 | } | |||
2685 | ||||
2686 | void CGOpenMPRuntime::emitForDispatchInit( | |||
2687 | CodeGenFunction &CGF, SourceLocation Loc, | |||
2688 | const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, | |||
2689 | bool Ordered, const DispatchRTInput &DispatchValues) { | |||
2690 | if (!CGF.HaveInsertPoint()) | |||
2691 | return; | |||
2692 | OpenMPSchedType Schedule = getRuntimeSchedule( | |||
2693 | ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered); | |||
2694 | assert(Ordered ||(static_cast <bool> (Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)) ? void (0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2697, __extension__ __PRETTY_FUNCTION__)) | |||
2695 | (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&(static_cast <bool> (Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)) ? void (0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2697, __extension__ __PRETTY_FUNCTION__)) | |||
2696 | Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&(static_cast <bool> (Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)) ? void (0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2697, __extension__ __PRETTY_FUNCTION__)) | |||
2697 | Schedule != OMP_sch_static_balanced_chunked))(static_cast <bool> (Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)) ? void (0) : __assert_fail ("Ordered || (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && Schedule != OMP_sch_static_balanced_chunked)" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2697, __extension__ __PRETTY_FUNCTION__)); | |||
2698 | // Call __kmpc_dispatch_init( | |||
2699 | // ident_t *loc, kmp_int32 tid, kmp_int32 schedule, | |||
2700 | // kmp_int[32|64] lower, kmp_int[32|64] upper, | |||
2701 | // kmp_int[32|64] stride, kmp_int[32|64] chunk); | |||
2702 | ||||
2703 | // If the Chunk was not specified in the clause - use default value 1. | |||
2704 | llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk | |||
2705 | : CGF.Builder.getIntN(IVSize, 1); | |||
2706 | llvm::Value *Args[] = { | |||
2707 | emitUpdateLocation(CGF, Loc), | |||
2708 | getThreadID(CGF, Loc), | |||
2709 | CGF.Builder.getInt32(addMonoNonMonoModifier( | |||
2710 | CGM, Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type | |||
2711 | DispatchValues.LB, // Lower | |||
2712 | DispatchValues.UB, // Upper | |||
2713 | CGF.Builder.getIntN(IVSize, 1), // Stride | |||
2714 | Chunk // Chunk | |||
2715 | }; | |||
2716 | CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args); | |||
2717 | } | |||
2718 | ||||
2719 | static void emitForStaticInitCall( | |||
2720 | CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId, | |||
2721 | llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule, | |||
2722 | OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, | |||
2723 | const CGOpenMPRuntime::StaticRTInput &Values) { | |||
2724 | if (!CGF.HaveInsertPoint()) | |||
2725 | return; | |||
2726 | ||||
2727 | assert(!Values.Ordered)(static_cast <bool> (!Values.Ordered) ? void (0) : __assert_fail ("!Values.Ordered", "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2727, __extension__ __PRETTY_FUNCTION__)); | |||
2728 | assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2732, __extension__ __PRETTY_FUNCTION__)) | |||
2729 | Schedule == OMP_sch_static_balanced_chunked ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2732, __extension__ __PRETTY_FUNCTION__)) | |||
2730 | Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2732, __extension__ __PRETTY_FUNCTION__)) | |||
2731 | Schedule == OMP_dist_sch_static ||(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2732, __extension__ __PRETTY_FUNCTION__)) | |||
2732 | Schedule == OMP_dist_sch_static_chunked)(static_cast <bool> (Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked ) ? void (0) : __assert_fail ("Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static || Schedule == OMP_dist_sch_static_chunked" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2732, __extension__ __PRETTY_FUNCTION__)); | |||
2733 | ||||
2734 | // Call __kmpc_for_static_init( | |||
2735 | // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype, | |||
2736 | // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower, | |||
2737 | // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride, | |||
2738 | // kmp_int[32|64] incr, kmp_int[32|64] chunk); | |||
2739 | llvm::Value *Chunk = Values.Chunk; | |||
2740 | if (Chunk == nullptr) { | |||
2741 | assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||(static_cast <bool> ((Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && "expected static non-chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && \"expected static non-chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2743, __extension__ __PRETTY_FUNCTION__)) | |||
2742 | Schedule == OMP_dist_sch_static) &&(static_cast <bool> ((Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && "expected static non-chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && \"expected static non-chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2743, __extension__ __PRETTY_FUNCTION__)) | |||
2743 | "expected static non-chunked schedule")(static_cast <bool> ((Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && "expected static non-chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static || Schedule == OMP_ord_static || Schedule == OMP_dist_sch_static) && \"expected static non-chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2743, __extension__ __PRETTY_FUNCTION__)); | |||
2744 | // If the Chunk was not specified in the clause - use default value 1. | |||
2745 | Chunk = CGF.Builder.getIntN(Values.IVSize, 1); | |||
2746 | } else { | |||
2747 | assert((Schedule == OMP_sch_static_chunked ||(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2751, __extension__ __PRETTY_FUNCTION__)) | |||
2748 | Schedule == OMP_sch_static_balanced_chunked ||(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2751, __extension__ __PRETTY_FUNCTION__)) | |||
2749 | Schedule == OMP_ord_static_chunked ||(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2751, __extension__ __PRETTY_FUNCTION__)) | |||
2750 | Schedule == OMP_dist_sch_static_chunked) &&(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2751, __extension__ __PRETTY_FUNCTION__)) | |||
2751 | "expected static chunked schedule")(static_cast <bool> ((Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked ) && "expected static chunked schedule") ? void (0) : __assert_fail ("(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static_balanced_chunked || Schedule == OMP_ord_static_chunked || Schedule == OMP_dist_sch_static_chunked) && \"expected static chunked schedule\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2751, __extension__ __PRETTY_FUNCTION__)); | |||
2752 | } | |||
2753 | llvm::Value *Args[] = { | |||
2754 | UpdateLocation, | |||
2755 | ThreadId, | |||
2756 | CGF.Builder.getInt32(addMonoNonMonoModifier(CGF.CGM, Schedule, M1, | |||
2757 | M2)), // Schedule type | |||
2758 | Values.IL.getPointer(), // &isLastIter | |||
2759 | Values.LB.getPointer(), // &LB | |||
2760 | Values.UB.getPointer(), // &UB | |||
2761 | Values.ST.getPointer(), // &Stride | |||
2762 | CGF.Builder.getIntN(Values.IVSize, 1), // Incr | |||
2763 | Chunk // Chunk | |||
2764 | }; | |||
2765 | CGF.EmitRuntimeCall(ForStaticInitFunction, Args); | |||
2766 | } | |||
2767 | ||||
2768 | void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF, | |||
2769 | SourceLocation Loc, | |||
2770 | OpenMPDirectiveKind DKind, | |||
2771 | const OpenMPScheduleTy &ScheduleKind, | |||
2772 | const StaticRTInput &Values) { | |||
2773 | OpenMPSchedType ScheduleNum = getRuntimeSchedule( | |||
2774 | ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered); | |||
2775 | assert(isOpenMPWorksharingDirective(DKind) &&(static_cast <bool> (isOpenMPWorksharingDirective(DKind ) && "Expected loop-based or sections-based directive." ) ? void (0) : __assert_fail ("isOpenMPWorksharingDirective(DKind) && \"Expected loop-based or sections-based directive.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2776, __extension__ __PRETTY_FUNCTION__)) | |||
2776 | "Expected loop-based or sections-based directive.")(static_cast <bool> (isOpenMPWorksharingDirective(DKind ) && "Expected loop-based or sections-based directive." ) ? void (0) : __assert_fail ("isOpenMPWorksharingDirective(DKind) && \"Expected loop-based or sections-based directive.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2776, __extension__ __PRETTY_FUNCTION__)); | |||
2777 | llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc, | |||
2778 | isOpenMPLoopDirective(DKind) | |||
2779 | ? OMP_IDENT_WORK_LOOP | |||
2780 | : OMP_IDENT_WORK_SECTIONS); | |||
2781 | llvm::Value *ThreadId = getThreadID(CGF, Loc); | |||
2782 | llvm::FunctionCallee StaticInitFunction = | |||
2783 | createForStaticInitFunction(Values.IVSize, Values.IVSigned, false); | |||
2784 | auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc); | |||
2785 | emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction, | |||
2786 | ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values); | |||
2787 | } | |||
2788 | ||||
2789 | void CGOpenMPRuntime::emitDistributeStaticInit( | |||
2790 | CodeGenFunction &CGF, SourceLocation Loc, | |||
2791 | OpenMPDistScheduleClauseKind SchedKind, | |||
2792 | const CGOpenMPRuntime::StaticRTInput &Values) { | |||
2793 | OpenMPSchedType ScheduleNum = | |||
2794 | getRuntimeSchedule(SchedKind, Values.Chunk != nullptr); | |||
2795 | llvm::Value *UpdatedLocation = | |||
2796 | emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE); | |||
2797 | llvm::Value *ThreadId = getThreadID(CGF, Loc); | |||
2798 | llvm::FunctionCallee StaticInitFunction; | |||
2799 | bool isGPUDistribute = | |||
2800 | CGM.getLangOpts().OpenMPIsDevice && | |||
2801 | (CGM.getTriple().isAMDGCN() || CGM.getTriple().isNVPTX()); | |||
2802 | StaticInitFunction = createForStaticInitFunction( | |||
2803 | Values.IVSize, Values.IVSigned, isGPUDistribute); | |||
2804 | ||||
2805 | emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction, | |||
2806 | ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown, | |||
2807 | OMPC_SCHEDULE_MODIFIER_unknown, Values); | |||
2808 | } | |||
2809 | ||||
2810 | void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF, | |||
2811 | SourceLocation Loc, | |||
2812 | OpenMPDirectiveKind DKind) { | |||
2813 | if (!CGF.HaveInsertPoint()) | |||
2814 | return; | |||
2815 | // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid); | |||
2816 | llvm::Value *Args[] = { | |||
2817 | emitUpdateLocation(CGF, Loc, | |||
2818 | isOpenMPDistributeDirective(DKind) | |||
2819 | ? OMP_IDENT_WORK_DISTRIBUTE | |||
2820 | : isOpenMPLoopDirective(DKind) | |||
2821 | ? OMP_IDENT_WORK_LOOP | |||
2822 | : OMP_IDENT_WORK_SECTIONS), | |||
2823 | getThreadID(CGF, Loc)}; | |||
2824 | auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc); | |||
2825 | if (isOpenMPDistributeDirective(DKind) && CGM.getLangOpts().OpenMPIsDevice && | |||
2826 | (CGM.getTriple().isAMDGCN() || CGM.getTriple().isNVPTX())) | |||
2827 | CGF.EmitRuntimeCall( | |||
2828 | OMPBuilder.getOrCreateRuntimeFunction( | |||
2829 | CGM.getModule(), OMPRTL___kmpc_distribute_static_fini), | |||
2830 | Args); | |||
2831 | else | |||
2832 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2833 | CGM.getModule(), OMPRTL___kmpc_for_static_fini), | |||
2834 | Args); | |||
2835 | } | |||
2836 | ||||
2837 | void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF, | |||
2838 | SourceLocation Loc, | |||
2839 | unsigned IVSize, | |||
2840 | bool IVSigned) { | |||
2841 | if (!CGF.HaveInsertPoint()) | |||
2842 | return; | |||
2843 | // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid); | |||
2844 | llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; | |||
2845 | CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args); | |||
2846 | } | |||
2847 | ||||
2848 | llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF, | |||
2849 | SourceLocation Loc, unsigned IVSize, | |||
2850 | bool IVSigned, Address IL, | |||
2851 | Address LB, Address UB, | |||
2852 | Address ST) { | |||
2853 | // Call __kmpc_dispatch_next( | |||
2854 | // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, | |||
2855 | // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, | |||
2856 | // kmp_int[32|64] *p_stride); | |||
2857 | llvm::Value *Args[] = { | |||
2858 | emitUpdateLocation(CGF, Loc), | |||
2859 | getThreadID(CGF, Loc), | |||
2860 | IL.getPointer(), // &isLastIter | |||
2861 | LB.getPointer(), // &Lower | |||
2862 | UB.getPointer(), // &Upper | |||
2863 | ST.getPointer() // &Stride | |||
2864 | }; | |||
2865 | llvm::Value *Call = | |||
2866 | CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args); | |||
2867 | return CGF.EmitScalarConversion( | |||
2868 | Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1), | |||
2869 | CGF.getContext().BoolTy, Loc); | |||
2870 | } | |||
2871 | ||||
2872 | void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF, | |||
2873 | llvm::Value *NumThreads, | |||
2874 | SourceLocation Loc) { | |||
2875 | if (!CGF.HaveInsertPoint()) | |||
2876 | return; | |||
2877 | // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads) | |||
2878 | llvm::Value *Args[] = { | |||
2879 | emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2880 | CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)}; | |||
2881 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2882 | CGM.getModule(), OMPRTL___kmpc_push_num_threads), | |||
2883 | Args); | |||
2884 | } | |||
2885 | ||||
2886 | void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF, | |||
2887 | ProcBindKind ProcBind, | |||
2888 | SourceLocation Loc) { | |||
2889 | if (!CGF.HaveInsertPoint()) | |||
2890 | return; | |||
2891 | assert(ProcBind != OMP_PROC_BIND_unknown && "Unsupported proc_bind value.")(static_cast <bool> (ProcBind != OMP_PROC_BIND_unknown && "Unsupported proc_bind value.") ? void (0) : __assert_fail ( "ProcBind != OMP_PROC_BIND_unknown && \"Unsupported proc_bind value.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 2891, __extension__ __PRETTY_FUNCTION__)); | |||
2892 | // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind) | |||
2893 | llvm::Value *Args[] = { | |||
2894 | emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), | |||
2895 | llvm::ConstantInt::get(CGM.IntTy, unsigned(ProcBind), /*isSigned=*/true)}; | |||
2896 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2897 | CGM.getModule(), OMPRTL___kmpc_push_proc_bind), | |||
2898 | Args); | |||
2899 | } | |||
2900 | ||||
2901 | void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>, | |||
2902 | SourceLocation Loc, llvm::AtomicOrdering AO) { | |||
2903 | if (CGF.CGM.getLangOpts().OpenMPIRBuilder) { | |||
2904 | OMPBuilder.createFlush(CGF.Builder); | |||
2905 | } else { | |||
2906 | if (!CGF.HaveInsertPoint()) | |||
2907 | return; | |||
2908 | // Build call void __kmpc_flush(ident_t *loc) | |||
2909 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
2910 | CGM.getModule(), OMPRTL___kmpc_flush), | |||
2911 | emitUpdateLocation(CGF, Loc)); | |||
2912 | } | |||
2913 | } | |||
2914 | ||||
2915 | namespace { | |||
2916 | /// Indexes of fields for type kmp_task_t. | |||
2917 | enum KmpTaskTFields { | |||
2918 | /// List of shared variables. | |||
2919 | KmpTaskTShareds, | |||
2920 | /// Task routine. | |||
2921 | KmpTaskTRoutine, | |||
2922 | /// Partition id for the untied tasks. | |||
2923 | KmpTaskTPartId, | |||
2924 | /// Function with call of destructors for private variables. | |||
2925 | Data1, | |||
2926 | /// Task priority. | |||
2927 | Data2, | |||
2928 | /// (Taskloops only) Lower bound. | |||
2929 | KmpTaskTLowerBound, | |||
2930 | /// (Taskloops only) Upper bound. | |||
2931 | KmpTaskTUpperBound, | |||
2932 | /// (Taskloops only) Stride. | |||
2933 | KmpTaskTStride, | |||
2934 | /// (Taskloops only) Is last iteration flag. | |||
2935 | KmpTaskTLastIter, | |||
2936 | /// (Taskloops only) Reduction data. | |||
2937 | KmpTaskTReductions, | |||
2938 | }; | |||
2939 | } // anonymous namespace | |||
2940 | ||||
2941 | void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() { | |||
2942 | // If we are in simd mode or there are no entries, we don't need to do | |||
2943 | // anything. | |||
2944 | if (CGM.getLangOpts().OpenMPSimd || OMPBuilder.OffloadInfoManager.empty()) | |||
2945 | return; | |||
2946 | ||||
2947 | llvm::OpenMPIRBuilder::EmitMetadataErrorReportFunctionTy &&ErrorReportFn = | |||
2948 | [this](llvm::OpenMPIRBuilder::EmitMetadataErrorKind Kind, | |||
2949 | const llvm::TargetRegionEntryInfo &EntryInfo) -> void { | |||
2950 | SourceLocation Loc; | |||
2951 | if (Kind != llvm::OpenMPIRBuilder::EMIT_MD_GLOBAL_VAR_LINK_ERROR) { | |||
2952 | for (auto I = CGM.getContext().getSourceManager().fileinfo_begin(), | |||
2953 | E = CGM.getContext().getSourceManager().fileinfo_end(); | |||
2954 | I != E; ++I) { | |||
2955 | if (I->getFirst()->getUniqueID().getDevice() == EntryInfo.DeviceID && | |||
2956 | I->getFirst()->getUniqueID().getFile() == EntryInfo.FileID) { | |||
2957 | Loc = CGM.getContext().getSourceManager().translateFileLineCol( | |||
2958 | I->getFirst(), EntryInfo.Line, 1); | |||
2959 | break; | |||
2960 | } | |||
2961 | } | |||
2962 | } | |||
2963 | switch (Kind) { | |||
2964 | case llvm::OpenMPIRBuilder::EMIT_MD_TARGET_REGION_ERROR: { | |||
2965 | unsigned DiagID = CGM.getDiags().getCustomDiagID( | |||
2966 | DiagnosticsEngine::Error, "Offloading entry for target region in " | |||
2967 | "%0 is incorrect: either the " | |||
2968 | "address or the ID is invalid."); | |||
2969 | CGM.getDiags().Report(Loc, DiagID) << EntryInfo.ParentName; | |||
2970 | } break; | |||
2971 | case llvm::OpenMPIRBuilder::EMIT_MD_DECLARE_TARGET_ERROR: { | |||
2972 | unsigned DiagID = CGM.getDiags().getCustomDiagID( | |||
2973 | DiagnosticsEngine::Error, "Offloading entry for declare target " | |||
2974 | "variable %0 is incorrect: the " | |||
2975 | "address is invalid."); | |||
2976 | CGM.getDiags().Report(Loc, DiagID) << EntryInfo.ParentName; | |||
2977 | } break; | |||
2978 | case llvm::OpenMPIRBuilder::EMIT_MD_GLOBAL_VAR_LINK_ERROR: { | |||
2979 | unsigned DiagID = CGM.getDiags().getCustomDiagID( | |||
2980 | DiagnosticsEngine::Error, | |||
2981 | "Offloading entry for declare target variable is incorrect: the " | |||
2982 | "address is invalid."); | |||
2983 | CGM.getDiags().Report(DiagID); | |||
2984 | } break; | |||
2985 | } | |||
2986 | }; | |||
2987 | ||||
2988 | OMPBuilder.createOffloadEntriesAndInfoMetadata(ErrorReportFn); | |||
2989 | } | |||
2990 | ||||
2991 | /// Loads all the offload entries information from the host IR | |||
2992 | /// metadata. | |||
2993 | void CGOpenMPRuntime::loadOffloadInfoMetadata() { | |||
2994 | // If we are in target mode, load the metadata from the host IR. This code has | |||
2995 | // to match the metadaata creation in createOffloadEntriesAndInfoMetadata(). | |||
2996 | ||||
2997 | if (!CGM.getLangOpts().OpenMPIsDevice) | |||
2998 | return; | |||
2999 | ||||
3000 | if (CGM.getLangOpts().OMPHostIRFile.empty()) | |||
3001 | return; | |||
3002 | ||||
3003 | auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile); | |||
3004 | if (auto EC = Buf.getError()) { | |||
3005 | CGM.getDiags().Report(diag::err_cannot_open_file) | |||
3006 | << CGM.getLangOpts().OMPHostIRFile << EC.message(); | |||
3007 | return; | |||
3008 | } | |||
3009 | ||||
3010 | llvm::LLVMContext C; | |||
3011 | auto ME = expectedToErrorOrAndEmitErrors( | |||
3012 | C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C)); | |||
3013 | ||||
3014 | if (auto EC = ME.getError()) { | |||
3015 | unsigned DiagID = CGM.getDiags().getCustomDiagID( | |||
3016 | DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'"); | |||
3017 | CGM.getDiags().Report(DiagID) | |||
3018 | << CGM.getLangOpts().OMPHostIRFile << EC.message(); | |||
3019 | return; | |||
3020 | } | |||
3021 | ||||
3022 | OMPBuilder.loadOffloadInfoMetadata(*ME.get()); | |||
3023 | } | |||
3024 | ||||
3025 | void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) { | |||
3026 | if (!KmpRoutineEntryPtrTy) { | |||
3027 | // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type. | |||
3028 | ASTContext &C = CGM.getContext(); | |||
3029 | QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy}; | |||
3030 | FunctionProtoType::ExtProtoInfo EPI; | |||
3031 | KmpRoutineEntryPtrQTy = C.getPointerType( | |||
3032 | C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI)); | |||
3033 | KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy); | |||
3034 | } | |||
3035 | } | |||
3036 | ||||
3037 | namespace { | |||
3038 | struct PrivateHelpersTy { | |||
3039 | PrivateHelpersTy(const Expr *OriginalRef, const VarDecl *Original, | |||
3040 | const VarDecl *PrivateCopy, const VarDecl *PrivateElemInit) | |||
3041 | : OriginalRef(OriginalRef), Original(Original), PrivateCopy(PrivateCopy), | |||
3042 | PrivateElemInit(PrivateElemInit) {} | |||
3043 | PrivateHelpersTy(const VarDecl *Original) : Original(Original) {} | |||
3044 | const Expr *OriginalRef = nullptr; | |||
3045 | const VarDecl *Original = nullptr; | |||
3046 | const VarDecl *PrivateCopy = nullptr; | |||
3047 | const VarDecl *PrivateElemInit = nullptr; | |||
3048 | bool isLocalPrivate() const { | |||
3049 | return !OriginalRef && !PrivateCopy && !PrivateElemInit; | |||
3050 | } | |||
3051 | }; | |||
3052 | typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy; | |||
3053 | } // anonymous namespace | |||
3054 | ||||
3055 | static bool isAllocatableDecl(const VarDecl *VD) { | |||
3056 | const VarDecl *CVD = VD->getCanonicalDecl(); | |||
3057 | if (!CVD->hasAttr<OMPAllocateDeclAttr>()) | |||
3058 | return false; | |||
3059 | const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>(); | |||
3060 | // Use the default allocation. | |||
3061 | return !(AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc && | |||
3062 | !AA->getAllocator()); | |||
3063 | } | |||
3064 | ||||
3065 | static RecordDecl * | |||
3066 | createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) { | |||
3067 | if (!Privates.empty()) { | |||
3068 | ASTContext &C = CGM.getContext(); | |||
3069 | // Build struct .kmp_privates_t. { | |||
3070 | // /* private vars */ | |||
3071 | // }; | |||
3072 | RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t"); | |||
3073 | RD->startDefinition(); | |||
3074 | for (const auto &Pair : Privates) { | |||
3075 | const VarDecl *VD = Pair.second.Original; | |||
3076 | QualType Type = VD->getType().getNonReferenceType(); | |||
3077 | // If the private variable is a local variable with lvalue ref type, | |||
3078 | // allocate the pointer instead of the pointee type. | |||
3079 | if (Pair.second.isLocalPrivate()) { | |||
3080 | if (VD->getType()->isLValueReferenceType()) | |||
3081 | Type = C.getPointerType(Type); | |||
3082 | if (isAllocatableDecl(VD)) | |||
3083 | Type = C.getPointerType(Type); | |||
3084 | } | |||
3085 | FieldDecl *FD = addFieldToRecordDecl(C, RD, Type); | |||
3086 | if (VD->hasAttrs()) { | |||
3087 | for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()), | |||
3088 | E(VD->getAttrs().end()); | |||
3089 | I != E; ++I) | |||
3090 | FD->addAttr(*I); | |||
3091 | } | |||
3092 | } | |||
3093 | RD->completeDefinition(); | |||
3094 | return RD; | |||
3095 | } | |||
3096 | return nullptr; | |||
3097 | } | |||
3098 | ||||
3099 | static RecordDecl * | |||
3100 | createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind, | |||
3101 | QualType KmpInt32Ty, | |||
3102 | QualType KmpRoutineEntryPointerQTy) { | |||
3103 | ASTContext &C = CGM.getContext(); | |||
3104 | // Build struct kmp_task_t { | |||
3105 | // void * shareds; | |||
3106 | // kmp_routine_entry_t routine; | |||
3107 | // kmp_int32 part_id; | |||
3108 | // kmp_cmplrdata_t data1; | |||
3109 | // kmp_cmplrdata_t data2; | |||
3110 | // For taskloops additional fields: | |||
3111 | // kmp_uint64 lb; | |||
3112 | // kmp_uint64 ub; | |||
3113 | // kmp_int64 st; | |||
3114 | // kmp_int32 liter; | |||
3115 | // void * reductions; | |||
3116 | // }; | |||
3117 | RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union); | |||
3118 | UD->startDefinition(); | |||
3119 | addFieldToRecordDecl(C, UD, KmpInt32Ty); | |||
3120 | addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy); | |||
3121 | UD->completeDefinition(); | |||
3122 | QualType KmpCmplrdataTy = C.getRecordType(UD); | |||
3123 | RecordDecl *RD = C.buildImplicitRecord("kmp_task_t"); | |||
3124 | RD->startDefinition(); | |||
3125 | addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
3126 | addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy); | |||
3127 | addFieldToRecordDecl(C, RD, KmpInt32Ty); | |||
3128 | addFieldToRecordDecl(C, RD, KmpCmplrdataTy); | |||
3129 | addFieldToRecordDecl(C, RD, KmpCmplrdataTy); | |||
3130 | if (isOpenMPTaskLoopDirective(Kind)) { | |||
3131 | QualType KmpUInt64Ty = | |||
3132 | CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); | |||
3133 | QualType KmpInt64Ty = | |||
3134 | CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); | |||
3135 | addFieldToRecordDecl(C, RD, KmpUInt64Ty); | |||
3136 | addFieldToRecordDecl(C, RD, KmpUInt64Ty); | |||
3137 | addFieldToRecordDecl(C, RD, KmpInt64Ty); | |||
3138 | addFieldToRecordDecl(C, RD, KmpInt32Ty); | |||
3139 | addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
3140 | } | |||
3141 | RD->completeDefinition(); | |||
3142 | return RD; | |||
3143 | } | |||
3144 | ||||
3145 | static RecordDecl * | |||
3146 | createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy, | |||
3147 | ArrayRef<PrivateDataTy> Privates) { | |||
3148 | ASTContext &C = CGM.getContext(); | |||
3149 | // Build struct kmp_task_t_with_privates { | |||
3150 | // kmp_task_t task_data; | |||
3151 | // .kmp_privates_t. privates; | |||
3152 | // }; | |||
3153 | RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates"); | |||
3154 | RD->startDefinition(); | |||
3155 | addFieldToRecordDecl(C, RD, KmpTaskTQTy); | |||
3156 | if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) | |||
3157 | addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD)); | |||
3158 | RD->completeDefinition(); | |||
3159 | return RD; | |||
3160 | } | |||
3161 | ||||
3162 | /// Emit a proxy function which accepts kmp_task_t as the second | |||
3163 | /// argument. | |||
3164 | /// \code | |||
3165 | /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { | |||
3166 | /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt, | |||
3167 | /// For taskloops: | |||
3168 | /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter, | |||
3169 | /// tt->reductions, tt->shareds); | |||
3170 | /// return 0; | |||
3171 | /// } | |||
3172 | /// \endcode | |||
3173 | static llvm::Function * | |||
3174 | emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc, | |||
3175 | OpenMPDirectiveKind Kind, QualType KmpInt32Ty, | |||
3176 | QualType KmpTaskTWithPrivatesPtrQTy, | |||
3177 | QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy, | |||
3178 | QualType SharedsPtrTy, llvm::Function *TaskFunction, | |||
3179 | llvm::Value *TaskPrivatesMap) { | |||
3180 | ASTContext &C = CGM.getContext(); | |||
3181 | FunctionArgList Args; | |||
3182 | ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty, | |||
3183 | ImplicitParamDecl::Other); | |||
3184 | ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3185 | KmpTaskTWithPrivatesPtrQTy.withRestrict(), | |||
3186 | ImplicitParamDecl::Other); | |||
3187 | Args.push_back(&GtidArg); | |||
3188 | Args.push_back(&TaskTypeArg); | |||
3189 | const auto &TaskEntryFnInfo = | |||
3190 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args); | |||
3191 | llvm::FunctionType *TaskEntryTy = | |||
3192 | CGM.getTypes().GetFunctionType(TaskEntryFnInfo); | |||
3193 | std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""}); | |||
3194 | auto *TaskEntry = llvm::Function::Create( | |||
3195 | TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule()); | |||
3196 | CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo); | |||
3197 | TaskEntry->setDoesNotRecurse(); | |||
3198 | CodeGenFunction CGF(CGM); | |||
3199 | CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args, | |||
3200 | Loc, Loc); | |||
3201 | ||||
3202 | // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map, | |||
3203 | // tt, | |||
3204 | // For taskloops: | |||
3205 | // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter, | |||
3206 | // tt->task_data.shareds); | |||
3207 | llvm::Value *GtidParam = CGF.EmitLoadOfScalar( | |||
3208 | CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc); | |||
3209 | LValue TDBase = CGF.EmitLoadOfPointerLValue( | |||
3210 | CGF.GetAddrOfLocalVar(&TaskTypeArg), | |||
3211 | KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); | |||
3212 | const auto *KmpTaskTWithPrivatesQTyRD = | |||
3213 | cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl()); | |||
3214 | LValue Base = | |||
3215 | CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3216 | const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl()); | |||
3217 | auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId); | |||
3218 | LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI); | |||
3219 | llvm::Value *PartidParam = PartIdLVal.getPointer(CGF); | |||
3220 | ||||
3221 | auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds); | |||
3222 | LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI); | |||
3223 | llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3224 | CGF.EmitLoadOfScalar(SharedsLVal, Loc), | |||
3225 | CGF.ConvertTypeForMem(SharedsPtrTy)); | |||
3226 | ||||
3227 | auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1); | |||
3228 | llvm::Value *PrivatesParam; | |||
3229 | if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) { | |||
3230 | LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI); | |||
3231 | PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3232 | PrivatesLVal.getPointer(CGF), CGF.VoidPtrTy); | |||
3233 | } else { | |||
3234 | PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
3235 | } | |||
3236 | ||||
3237 | llvm::Value *CommonArgs[] = { | |||
3238 | GtidParam, PartidParam, PrivatesParam, TaskPrivatesMap, | |||
3239 | CGF.Builder | |||
3240 | .CreatePointerBitCastOrAddrSpaceCast(TDBase.getAddress(CGF), | |||
3241 | CGF.VoidPtrTy, CGF.Int8Ty) | |||
3242 | .getPointer()}; | |||
3243 | SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs), | |||
3244 | std::end(CommonArgs)); | |||
3245 | if (isOpenMPTaskLoopDirective(Kind)) { | |||
3246 | auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound); | |||
3247 | LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI); | |||
3248 | llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc); | |||
3249 | auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound); | |||
3250 | LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI); | |||
3251 | llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc); | |||
3252 | auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride); | |||
3253 | LValue StLVal = CGF.EmitLValueForField(Base, *StFI); | |||
3254 | llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc); | |||
3255 | auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter); | |||
3256 | LValue LILVal = CGF.EmitLValueForField(Base, *LIFI); | |||
3257 | llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc); | |||
3258 | auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions); | |||
3259 | LValue RLVal = CGF.EmitLValueForField(Base, *RFI); | |||
3260 | llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc); | |||
3261 | CallArgs.push_back(LBParam); | |||
3262 | CallArgs.push_back(UBParam); | |||
3263 | CallArgs.push_back(StParam); | |||
3264 | CallArgs.push_back(LIParam); | |||
3265 | CallArgs.push_back(RParam); | |||
3266 | } | |||
3267 | CallArgs.push_back(SharedsParam); | |||
3268 | ||||
3269 | CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction, | |||
3270 | CallArgs); | |||
3271 | CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)), | |||
3272 | CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty)); | |||
3273 | CGF.FinishFunction(); | |||
3274 | return TaskEntry; | |||
3275 | } | |||
3276 | ||||
3277 | static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM, | |||
3278 | SourceLocation Loc, | |||
3279 | QualType KmpInt32Ty, | |||
3280 | QualType KmpTaskTWithPrivatesPtrQTy, | |||
3281 | QualType KmpTaskTWithPrivatesQTy) { | |||
3282 | ASTContext &C = CGM.getContext(); | |||
3283 | FunctionArgList Args; | |||
3284 | ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty, | |||
3285 | ImplicitParamDecl::Other); | |||
3286 | ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3287 | KmpTaskTWithPrivatesPtrQTy.withRestrict(), | |||
3288 | ImplicitParamDecl::Other); | |||
3289 | Args.push_back(&GtidArg); | |||
3290 | Args.push_back(&TaskTypeArg); | |||
3291 | const auto &DestructorFnInfo = | |||
3292 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args); | |||
3293 | llvm::FunctionType *DestructorFnTy = | |||
3294 | CGM.getTypes().GetFunctionType(DestructorFnInfo); | |||
3295 | std::string Name = | |||
3296 | CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""}); | |||
3297 | auto *DestructorFn = | |||
3298 | llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage, | |||
3299 | Name, &CGM.getModule()); | |||
3300 | CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn, | |||
3301 | DestructorFnInfo); | |||
3302 | DestructorFn->setDoesNotRecurse(); | |||
3303 | CodeGenFunction CGF(CGM); | |||
3304 | CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo, | |||
3305 | Args, Loc, Loc); | |||
3306 | ||||
3307 | LValue Base = CGF.EmitLoadOfPointerLValue( | |||
3308 | CGF.GetAddrOfLocalVar(&TaskTypeArg), | |||
3309 | KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); | |||
3310 | const auto *KmpTaskTWithPrivatesQTyRD = | |||
3311 | cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl()); | |||
3312 | auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3313 | Base = CGF.EmitLValueForField(Base, *FI); | |||
3314 | for (const auto *Field : | |||
3315 | cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) { | |||
3316 | if (QualType::DestructionKind DtorKind = | |||
3317 | Field->getType().isDestructedType()) { | |||
3318 | LValue FieldLValue = CGF.EmitLValueForField(Base, Field); | |||
3319 | CGF.pushDestroy(DtorKind, FieldLValue.getAddress(CGF), Field->getType()); | |||
3320 | } | |||
3321 | } | |||
3322 | CGF.FinishFunction(); | |||
3323 | return DestructorFn; | |||
3324 | } | |||
3325 | ||||
3326 | /// Emit a privates mapping function for correct handling of private and | |||
3327 | /// firstprivate variables. | |||
3328 | /// \code | |||
3329 | /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1> | |||
3330 | /// **noalias priv1,..., <tyn> **noalias privn) { | |||
3331 | /// *priv1 = &.privates.priv1; | |||
3332 | /// ...; | |||
3333 | /// *privn = &.privates.privn; | |||
3334 | /// } | |||
3335 | /// \endcode | |||
3336 | static llvm::Value * | |||
3337 | emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc, | |||
3338 | const OMPTaskDataTy &Data, QualType PrivatesQTy, | |||
3339 | ArrayRef<PrivateDataTy> Privates) { | |||
3340 | ASTContext &C = CGM.getContext(); | |||
3341 | FunctionArgList Args; | |||
3342 | ImplicitParamDecl TaskPrivatesArg( | |||
3343 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3344 | C.getPointerType(PrivatesQTy).withConst().withRestrict(), | |||
3345 | ImplicitParamDecl::Other); | |||
3346 | Args.push_back(&TaskPrivatesArg); | |||
3347 | llvm::DenseMap<CanonicalDeclPtr<const VarDecl>, unsigned> PrivateVarsPos; | |||
3348 | unsigned Counter = 1; | |||
3349 | for (const Expr *E : Data.PrivateVars) { | |||
3350 | Args.push_back(ImplicitParamDecl::Create( | |||
3351 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3352 | C.getPointerType(C.getPointerType(E->getType())) | |||
3353 | .withConst() | |||
3354 | .withRestrict(), | |||
3355 | ImplicitParamDecl::Other)); | |||
3356 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3357 | PrivateVarsPos[VD] = Counter; | |||
3358 | ++Counter; | |||
3359 | } | |||
3360 | for (const Expr *E : Data.FirstprivateVars) { | |||
3361 | Args.push_back(ImplicitParamDecl::Create( | |||
3362 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3363 | C.getPointerType(C.getPointerType(E->getType())) | |||
3364 | .withConst() | |||
3365 | .withRestrict(), | |||
3366 | ImplicitParamDecl::Other)); | |||
3367 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3368 | PrivateVarsPos[VD] = Counter; | |||
3369 | ++Counter; | |||
3370 | } | |||
3371 | for (const Expr *E : Data.LastprivateVars) { | |||
3372 | Args.push_back(ImplicitParamDecl::Create( | |||
3373 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3374 | C.getPointerType(C.getPointerType(E->getType())) | |||
3375 | .withConst() | |||
3376 | .withRestrict(), | |||
3377 | ImplicitParamDecl::Other)); | |||
3378 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3379 | PrivateVarsPos[VD] = Counter; | |||
3380 | ++Counter; | |||
3381 | } | |||
3382 | for (const VarDecl *VD : Data.PrivateLocals) { | |||
3383 | QualType Ty = VD->getType().getNonReferenceType(); | |||
3384 | if (VD->getType()->isLValueReferenceType()) | |||
3385 | Ty = C.getPointerType(Ty); | |||
3386 | if (isAllocatableDecl(VD)) | |||
3387 | Ty = C.getPointerType(Ty); | |||
3388 | Args.push_back(ImplicitParamDecl::Create( | |||
3389 | C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3390 | C.getPointerType(C.getPointerType(Ty)).withConst().withRestrict(), | |||
3391 | ImplicitParamDecl::Other)); | |||
3392 | PrivateVarsPos[VD] = Counter; | |||
3393 | ++Counter; | |||
3394 | } | |||
3395 | const auto &TaskPrivatesMapFnInfo = | |||
3396 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
3397 | llvm::FunctionType *TaskPrivatesMapTy = | |||
3398 | CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo); | |||
3399 | std::string Name = | |||
3400 | CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""}); | |||
3401 | auto *TaskPrivatesMap = llvm::Function::Create( | |||
3402 | TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name, | |||
3403 | &CGM.getModule()); | |||
3404 | CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap, | |||
3405 | TaskPrivatesMapFnInfo); | |||
3406 | if (CGM.getLangOpts().Optimize) { | |||
3407 | TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline); | |||
3408 | TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone); | |||
3409 | TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline); | |||
3410 | } | |||
3411 | CodeGenFunction CGF(CGM); | |||
3412 | CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap, | |||
3413 | TaskPrivatesMapFnInfo, Args, Loc, Loc); | |||
3414 | ||||
3415 | // *privi = &.privates.privi; | |||
3416 | LValue Base = CGF.EmitLoadOfPointerLValue( | |||
3417 | CGF.GetAddrOfLocalVar(&TaskPrivatesArg), | |||
3418 | TaskPrivatesArg.getType()->castAs<PointerType>()); | |||
3419 | const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl()); | |||
3420 | Counter = 0; | |||
3421 | for (const FieldDecl *Field : PrivatesQTyRD->fields()) { | |||
3422 | LValue FieldLVal = CGF.EmitLValueForField(Base, Field); | |||
3423 | const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]]; | |||
3424 | LValue RefLVal = | |||
3425 | CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType()); | |||
3426 | LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue( | |||
3427 | RefLVal.getAddress(CGF), RefLVal.getType()->castAs<PointerType>()); | |||
3428 | CGF.EmitStoreOfScalar(FieldLVal.getPointer(CGF), RefLoadLVal); | |||
3429 | ++Counter; | |||
3430 | } | |||
3431 | CGF.FinishFunction(); | |||
3432 | return TaskPrivatesMap; | |||
3433 | } | |||
3434 | ||||
3435 | /// Emit initialization for private variables in task-based directives. | |||
3436 | static void emitPrivatesInit(CodeGenFunction &CGF, | |||
3437 | const OMPExecutableDirective &D, | |||
3438 | Address KmpTaskSharedsPtr, LValue TDBase, | |||
3439 | const RecordDecl *KmpTaskTWithPrivatesQTyRD, | |||
3440 | QualType SharedsTy, QualType SharedsPtrTy, | |||
3441 | const OMPTaskDataTy &Data, | |||
3442 | ArrayRef<PrivateDataTy> Privates, bool ForDup) { | |||
3443 | ASTContext &C = CGF.getContext(); | |||
3444 | auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3445 | LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI); | |||
3446 | OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind()) | |||
3447 | ? OMPD_taskloop | |||
3448 | : OMPD_task; | |||
3449 | const CapturedStmt &CS = *D.getCapturedStmt(Kind); | |||
3450 | CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS); | |||
3451 | LValue SrcBase; | |||
3452 | bool IsTargetTask = | |||
3453 | isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) || | |||
3454 | isOpenMPTargetExecutionDirective(D.getDirectiveKind()); | |||
3455 | // For target-based directives skip 4 firstprivate arrays BasePointersArray, | |||
3456 | // PointersArray, SizesArray, and MappersArray. The original variables for | |||
3457 | // these arrays are not captured and we get their addresses explicitly. | |||
3458 | if ((!IsTargetTask && !Data.FirstprivateVars.empty() && ForDup) || | |||
3459 | (IsTargetTask && KmpTaskSharedsPtr.isValid())) { | |||
3460 | SrcBase = CGF.MakeAddrLValue( | |||
3461 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3462 | KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy), | |||
3463 | CGF.ConvertTypeForMem(SharedsTy)), | |||
3464 | SharedsTy); | |||
3465 | } | |||
3466 | FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin(); | |||
3467 | for (const PrivateDataTy &Pair : Privates) { | |||
3468 | // Do not initialize private locals. | |||
3469 | if (Pair.second.isLocalPrivate()) { | |||
3470 | ++FI; | |||
3471 | continue; | |||
3472 | } | |||
3473 | const VarDecl *VD = Pair.second.PrivateCopy; | |||
3474 | const Expr *Init = VD->getAnyInitializer(); | |||
3475 | if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) && | |||
3476 | !CGF.isTrivialInitializer(Init)))) { | |||
3477 | LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI); | |||
3478 | if (const VarDecl *Elem = Pair.second.PrivateElemInit) { | |||
3479 | const VarDecl *OriginalVD = Pair.second.Original; | |||
3480 | // Check if the variable is the target-based BasePointersArray, | |||
3481 | // PointersArray, SizesArray, or MappersArray. | |||
3482 | LValue SharedRefLValue; | |||
3483 | QualType Type = PrivateLValue.getType(); | |||
3484 | const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD); | |||
3485 | if (IsTargetTask && !SharedField) { | |||
3486 | assert(isa<ImplicitParamDecl>(OriginalVD) &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3493, __extension__ __PRETTY_FUNCTION__)) | |||
3487 | isa<CapturedDecl>(OriginalVD->getDeclContext()) &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3493, __extension__ __PRETTY_FUNCTION__)) | |||
3488 | cast<CapturedDecl>(OriginalVD->getDeclContext())(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3493, __extension__ __PRETTY_FUNCTION__)) | |||
3489 | ->getNumParams() == 0 &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3493, __extension__ __PRETTY_FUNCTION__)) | |||
3490 | isa<TranslationUnitDecl>((static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3493, __extension__ __PRETTY_FUNCTION__)) | |||
3491 | cast<CapturedDecl>(OriginalVD->getDeclContext())(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3493, __extension__ __PRETTY_FUNCTION__)) | |||
3492 | ->getDeclContext()) &&(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3493, __extension__ __PRETTY_FUNCTION__)) | |||
3493 | "Expected artificial target data variable.")(static_cast <bool> (isa<ImplicitParamDecl>(OriginalVD ) && isa<CapturedDecl>(OriginalVD->getDeclContext ()) && cast<CapturedDecl>(OriginalVD->getDeclContext ()) ->getNumParams() == 0 && isa<TranslationUnitDecl >( cast<CapturedDecl>(OriginalVD->getDeclContext( )) ->getDeclContext()) && "Expected artificial target data variable." ) ? void (0) : __assert_fail ("isa<ImplicitParamDecl>(OriginalVD) && isa<CapturedDecl>(OriginalVD->getDeclContext()) && cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getNumParams() == 0 && isa<TranslationUnitDecl>( cast<CapturedDecl>(OriginalVD->getDeclContext()) ->getDeclContext()) && \"Expected artificial target data variable.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3493, __extension__ __PRETTY_FUNCTION__)); | |||
3494 | SharedRefLValue = | |||
3495 | CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type); | |||
3496 | } else if (ForDup) { | |||
3497 | SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField); | |||
3498 | SharedRefLValue = CGF.MakeAddrLValue( | |||
3499 | SharedRefLValue.getAddress(CGF).withAlignment( | |||
3500 | C.getDeclAlign(OriginalVD)), | |||
3501 | SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl), | |||
3502 | SharedRefLValue.getTBAAInfo()); | |||
3503 | } else if (CGF.LambdaCaptureFields.count( | |||
3504 | Pair.second.Original->getCanonicalDecl()) > 0 || | |||
3505 | isa_and_nonnull<BlockDecl>(CGF.CurCodeDecl)) { | |||
3506 | SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef); | |||
3507 | } else { | |||
3508 | // Processing for implicitly captured variables. | |||
3509 | InlinedOpenMPRegionRAII Region( | |||
3510 | CGF, [](CodeGenFunction &, PrePostActionTy &) {}, OMPD_unknown, | |||
3511 | /*HasCancel=*/false, /*NoInheritance=*/true); | |||
3512 | SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef); | |||
3513 | } | |||
3514 | if (Type->isArrayType()) { | |||
3515 | // Initialize firstprivate array. | |||
3516 | if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) { | |||
3517 | // Perform simple memcpy. | |||
3518 | CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type); | |||
3519 | } else { | |||
3520 | // Initialize firstprivate array using element-by-element | |||
3521 | // initialization. | |||
3522 | CGF.EmitOMPAggregateAssign( | |||
3523 | PrivateLValue.getAddress(CGF), SharedRefLValue.getAddress(CGF), | |||
3524 | Type, | |||
3525 | [&CGF, Elem, Init, &CapturesInfo](Address DestElement, | |||
3526 | Address SrcElement) { | |||
3527 | // Clean up any temporaries needed by the initialization. | |||
3528 | CodeGenFunction::OMPPrivateScope InitScope(CGF); | |||
3529 | InitScope.addPrivate(Elem, SrcElement); | |||
3530 | (void)InitScope.Privatize(); | |||
3531 | // Emit initialization for single element. | |||
3532 | CodeGenFunction::CGCapturedStmtRAII CapInfoRAII( | |||
3533 | CGF, &CapturesInfo); | |||
3534 | CGF.EmitAnyExprToMem(Init, DestElement, | |||
3535 | Init->getType().getQualifiers(), | |||
3536 | /*IsInitializer=*/false); | |||
3537 | }); | |||
3538 | } | |||
3539 | } else { | |||
3540 | CodeGenFunction::OMPPrivateScope InitScope(CGF); | |||
3541 | InitScope.addPrivate(Elem, SharedRefLValue.getAddress(CGF)); | |||
3542 | (void)InitScope.Privatize(); | |||
3543 | CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo); | |||
3544 | CGF.EmitExprAsInit(Init, VD, PrivateLValue, | |||
3545 | /*capturedByInit=*/false); | |||
3546 | } | |||
3547 | } else { | |||
3548 | CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false); | |||
3549 | } | |||
3550 | } | |||
3551 | ++FI; | |||
3552 | } | |||
3553 | } | |||
3554 | ||||
3555 | /// Check if duplication function is required for taskloops. | |||
3556 | static bool checkInitIsRequired(CodeGenFunction &CGF, | |||
3557 | ArrayRef<PrivateDataTy> Privates) { | |||
3558 | bool InitRequired = false; | |||
3559 | for (const PrivateDataTy &Pair : Privates) { | |||
3560 | if (Pair.second.isLocalPrivate()) | |||
3561 | continue; | |||
3562 | const VarDecl *VD = Pair.second.PrivateCopy; | |||
3563 | const Expr *Init = VD->getAnyInitializer(); | |||
3564 | InitRequired = InitRequired || (isa_and_nonnull<CXXConstructExpr>(Init) && | |||
3565 | !CGF.isTrivialInitializer(Init)); | |||
3566 | if (InitRequired) | |||
3567 | break; | |||
3568 | } | |||
3569 | return InitRequired; | |||
3570 | } | |||
3571 | ||||
3572 | ||||
3573 | /// Emit task_dup function (for initialization of | |||
3574 | /// private/firstprivate/lastprivate vars and last_iter flag) | |||
3575 | /// \code | |||
3576 | /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int | |||
3577 | /// lastpriv) { | |||
3578 | /// // setup lastprivate flag | |||
3579 | /// task_dst->last = lastpriv; | |||
3580 | /// // could be constructor calls here... | |||
3581 | /// } | |||
3582 | /// \endcode | |||
3583 | static llvm::Value * | |||
3584 | emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc, | |||
3585 | const OMPExecutableDirective &D, | |||
3586 | QualType KmpTaskTWithPrivatesPtrQTy, | |||
3587 | const RecordDecl *KmpTaskTWithPrivatesQTyRD, | |||
3588 | const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy, | |||
3589 | QualType SharedsPtrTy, const OMPTaskDataTy &Data, | |||
3590 | ArrayRef<PrivateDataTy> Privates, bool WithLastIter) { | |||
3591 | ASTContext &C = CGM.getContext(); | |||
3592 | FunctionArgList Args; | |||
3593 | ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3594 | KmpTaskTWithPrivatesPtrQTy, | |||
3595 | ImplicitParamDecl::Other); | |||
3596 | ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
3597 | KmpTaskTWithPrivatesPtrQTy, | |||
3598 | ImplicitParamDecl::Other); | |||
3599 | ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy, | |||
3600 | ImplicitParamDecl::Other); | |||
3601 | Args.push_back(&DstArg); | |||
3602 | Args.push_back(&SrcArg); | |||
3603 | Args.push_back(&LastprivArg); | |||
3604 | const auto &TaskDupFnInfo = | |||
3605 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
3606 | llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo); | |||
3607 | std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""}); | |||
3608 | auto *TaskDup = llvm::Function::Create( | |||
3609 | TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule()); | |||
3610 | CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo); | |||
3611 | TaskDup->setDoesNotRecurse(); | |||
3612 | CodeGenFunction CGF(CGM); | |||
3613 | CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc, | |||
3614 | Loc); | |||
3615 | ||||
3616 | LValue TDBase = CGF.EmitLoadOfPointerLValue( | |||
3617 | CGF.GetAddrOfLocalVar(&DstArg), | |||
3618 | KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); | |||
3619 | // task_dst->liter = lastpriv; | |||
3620 | if (WithLastIter) { | |||
3621 | auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter); | |||
3622 | LValue Base = CGF.EmitLValueForField( | |||
3623 | TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3624 | LValue LILVal = CGF.EmitLValueForField(Base, *LIFI); | |||
3625 | llvm::Value *Lastpriv = CGF.EmitLoadOfScalar( | |||
3626 | CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc); | |||
3627 | CGF.EmitStoreOfScalar(Lastpriv, LILVal); | |||
3628 | } | |||
3629 | ||||
3630 | // Emit initial values for private copies (if any). | |||
3631 | assert(!Privates.empty())(static_cast <bool> (!Privates.empty()) ? void (0) : __assert_fail ("!Privates.empty()", "clang/lib/CodeGen/CGOpenMPRuntime.cpp" , 3631, __extension__ __PRETTY_FUNCTION__)); | |||
3632 | Address KmpTaskSharedsPtr = Address::invalid(); | |||
3633 | if (!Data.FirstprivateVars.empty()) { | |||
3634 | LValue TDBase = CGF.EmitLoadOfPointerLValue( | |||
3635 | CGF.GetAddrOfLocalVar(&SrcArg), | |||
3636 | KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); | |||
3637 | LValue Base = CGF.EmitLValueForField( | |||
3638 | TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3639 | KmpTaskSharedsPtr = Address( | |||
3640 | CGF.EmitLoadOfScalar(CGF.EmitLValueForField( | |||
3641 | Base, *std::next(KmpTaskTQTyRD->field_begin(), | |||
3642 | KmpTaskTShareds)), | |||
3643 | Loc), | |||
3644 | CGF.Int8Ty, CGM.getNaturalTypeAlignment(SharedsTy)); | |||
3645 | } | |||
3646 | emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD, | |||
3647 | SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true); | |||
3648 | CGF.FinishFunction(); | |||
3649 | return TaskDup; | |||
3650 | } | |||
3651 | ||||
3652 | /// Checks if destructor function is required to be generated. | |||
3653 | /// \return true if cleanups are required, false otherwise. | |||
3654 | static bool | |||
3655 | checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD, | |||
3656 | ArrayRef<PrivateDataTy> Privates) { | |||
3657 | for (const PrivateDataTy &P : Privates) { | |||
3658 | if (P.second.isLocalPrivate()) | |||
3659 | continue; | |||
3660 | QualType Ty = P.second.Original->getType().getNonReferenceType(); | |||
3661 | if (Ty.isDestructedType()) | |||
3662 | return true; | |||
3663 | } | |||
3664 | return false; | |||
3665 | } | |||
3666 | ||||
3667 | namespace { | |||
3668 | /// Loop generator for OpenMP iterator expression. | |||
3669 | class OMPIteratorGeneratorScope final | |||
3670 | : public CodeGenFunction::OMPPrivateScope { | |||
3671 | CodeGenFunction &CGF; | |||
3672 | const OMPIteratorExpr *E = nullptr; | |||
3673 | SmallVector<CodeGenFunction::JumpDest, 4> ContDests; | |||
3674 | SmallVector<CodeGenFunction::JumpDest, 4> ExitDests; | |||
3675 | OMPIteratorGeneratorScope() = delete; | |||
3676 | OMPIteratorGeneratorScope(OMPIteratorGeneratorScope &) = delete; | |||
3677 | ||||
3678 | public: | |||
3679 | OMPIteratorGeneratorScope(CodeGenFunction &CGF, const OMPIteratorExpr *E) | |||
3680 | : CodeGenFunction::OMPPrivateScope(CGF), CGF(CGF), E(E) { | |||
3681 | if (!E) | |||
3682 | return; | |||
3683 | SmallVector<llvm::Value *, 4> Uppers; | |||
3684 | for (unsigned I = 0, End = E->numOfIterators(); I < End; ++I) { | |||
3685 | Uppers.push_back(CGF.EmitScalarExpr(E->getHelper(I).Upper)); | |||
3686 | const auto *VD = cast<VarDecl>(E->getIteratorDecl(I)); | |||
3687 | addPrivate(VD, CGF.CreateMemTemp(VD->getType(), VD->getName())); | |||
3688 | const OMPIteratorHelperData &HelperData = E->getHelper(I); | |||
3689 | addPrivate( | |||
3690 | HelperData.CounterVD, | |||
3691 | CGF.CreateMemTemp(HelperData.CounterVD->getType(), "counter.addr")); | |||
3692 | } | |||
3693 | Privatize(); | |||
3694 | ||||
3695 | for (unsigned I = 0, End = E->numOfIterators(); I < End; ++I) { | |||
3696 | const OMPIteratorHelperData &HelperData = E->getHelper(I); | |||
3697 | LValue CLVal = | |||
3698 | CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(HelperData.CounterVD), | |||
3699 | HelperData.CounterVD->getType()); | |||
3700 | // Counter = 0; | |||
3701 | CGF.EmitStoreOfScalar( | |||
3702 | llvm::ConstantInt::get(CLVal.getAddress(CGF).getElementType(), 0), | |||
3703 | CLVal); | |||
3704 | CodeGenFunction::JumpDest &ContDest = | |||
3705 | ContDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.cont")); | |||
3706 | CodeGenFunction::JumpDest &ExitDest = | |||
3707 | ExitDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.exit")); | |||
3708 | // N = <number-of_iterations>; | |||
3709 | llvm::Value *N = Uppers[I]; | |||
3710 | // cont: | |||
3711 | // if (Counter < N) goto body; else goto exit; | |||
3712 | CGF.EmitBlock(ContDest.getBlock()); | |||
3713 | auto *CVal = | |||
3714 | CGF.EmitLoadOfScalar(CLVal, HelperData.CounterVD->getLocation()); | |||
3715 | llvm::Value *Cmp = | |||
3716 | HelperData.CounterVD->getType()->isSignedIntegerOrEnumerationType() | |||
3717 | ? CGF.Builder.CreateICmpSLT(CVal, N) | |||
3718 | : CGF.Builder.CreateICmpULT(CVal, N); | |||
3719 | llvm::BasicBlock *BodyBB = CGF.createBasicBlock("iter.body"); | |||
3720 | CGF.Builder.CreateCondBr(Cmp, BodyBB, ExitDest.getBlock()); | |||
3721 | // body: | |||
3722 | CGF.EmitBlock(BodyBB); | |||
3723 | // Iteri = Begini + Counter * Stepi; | |||
3724 | CGF.EmitIgnoredExpr(HelperData.Update); | |||
3725 | } | |||
3726 | } | |||
3727 | ~OMPIteratorGeneratorScope() { | |||
3728 | if (!E) | |||
3729 | return; | |||
3730 | for (unsigned I = E->numOfIterators(); I > 0; --I) { | |||
3731 | // Counter = Counter + 1; | |||
3732 | const OMPIteratorHelperData &HelperData = E->getHelper(I - 1); | |||
3733 | CGF.EmitIgnoredExpr(HelperData.CounterUpdate); | |||
3734 | // goto cont; | |||
3735 | CGF.EmitBranchThroughCleanup(ContDests[I - 1]); | |||
3736 | // exit: | |||
3737 | CGF.EmitBlock(ExitDests[I - 1].getBlock(), /*IsFinished=*/I == 1); | |||
3738 | } | |||
3739 | } | |||
3740 | }; | |||
3741 | } // namespace | |||
3742 | ||||
3743 | static std::pair<llvm::Value *, llvm::Value *> | |||
3744 | getPointerAndSize(CodeGenFunction &CGF, const Expr *E) { | |||
3745 | const auto *OASE = dyn_cast<OMPArrayShapingExpr>(E); | |||
3746 | llvm::Value *Addr; | |||
3747 | if (OASE) { | |||
3748 | const Expr *Base = OASE->getBase(); | |||
3749 | Addr = CGF.EmitScalarExpr(Base); | |||
3750 | } else { | |||
3751 | Addr = CGF.EmitLValue(E).getPointer(CGF); | |||
3752 | } | |||
3753 | llvm::Value *SizeVal; | |||
3754 | QualType Ty = E->getType(); | |||
3755 | if (OASE) { | |||
3756 | SizeVal = CGF.getTypeSize(OASE->getBase()->getType()->getPointeeType()); | |||
3757 | for (const Expr *SE : OASE->getDimensions()) { | |||
3758 | llvm::Value *Sz = CGF.EmitScalarExpr(SE); | |||
3759 | Sz = CGF.EmitScalarConversion( | |||
3760 | Sz, SE->getType(), CGF.getContext().getSizeType(), SE->getExprLoc()); | |||
3761 | SizeVal = CGF.Builder.CreateNUWMul(SizeVal, Sz); | |||
3762 | } | |||
3763 | } else if (const auto *ASE = | |||
3764 | dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) { | |||
3765 | LValue UpAddrLVal = | |||
3766 | CGF.EmitOMPArraySectionExpr(ASE, /*IsLowerBound=*/false); | |||
3767 | Address UpAddrAddress = UpAddrLVal.getAddress(CGF); | |||
3768 | llvm::Value *UpAddr = CGF.Builder.CreateConstGEP1_32( | |||
3769 | UpAddrAddress.getElementType(), UpAddrAddress.getPointer(), /*Idx0=*/1); | |||
3770 | llvm::Value *LowIntPtr = CGF.Builder.CreatePtrToInt(Addr, CGF.SizeTy); | |||
3771 | llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGF.SizeTy); | |||
3772 | SizeVal = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr); | |||
3773 | } else { | |||
3774 | SizeVal = CGF.getTypeSize(Ty); | |||
3775 | } | |||
3776 | return std::make_pair(Addr, SizeVal); | |||
3777 | } | |||
3778 | ||||
3779 | /// Builds kmp_depend_info, if it is not built yet, and builds flags type. | |||
3780 | static void getKmpAffinityType(ASTContext &C, QualType &KmpTaskAffinityInfoTy) { | |||
3781 | QualType FlagsTy = C.getIntTypeForBitwidth(32, /*Signed=*/false); | |||
3782 | if (KmpTaskAffinityInfoTy.isNull()) { | |||
3783 | RecordDecl *KmpAffinityInfoRD = | |||
3784 | C.buildImplicitRecord("kmp_task_affinity_info_t"); | |||
3785 | KmpAffinityInfoRD->startDefinition(); | |||
3786 | addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getIntPtrType()); | |||
3787 | addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getSizeType()); | |||
3788 | addFieldToRecordDecl(C, KmpAffinityInfoRD, FlagsTy); | |||
3789 | KmpAffinityInfoRD->completeDefinition(); | |||
3790 | KmpTaskAffinityInfoTy = C.getRecordType(KmpAffinityInfoRD); | |||
3791 | } | |||
3792 | } | |||
3793 | ||||
3794 | CGOpenMPRuntime::TaskResultTy | |||
3795 | CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, | |||
3796 | const OMPExecutableDirective &D, | |||
3797 | llvm::Function *TaskFunction, QualType SharedsTy, | |||
3798 | Address Shareds, const OMPTaskDataTy &Data) { | |||
3799 | ASTContext &C = CGM.getContext(); | |||
3800 | llvm::SmallVector<PrivateDataTy, 4> Privates; | |||
3801 | // Aggregate privates and sort them by the alignment. | |||
3802 | const auto *I = Data.PrivateCopies.begin(); | |||
3803 | for (const Expr *E : Data.PrivateVars) { | |||
3804 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3805 | Privates.emplace_back( | |||
3806 | C.getDeclAlign(VD), | |||
3807 | PrivateHelpersTy(E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), | |||
3808 | /*PrivateElemInit=*/nullptr)); | |||
3809 | ++I; | |||
3810 | } | |||
3811 | I = Data.FirstprivateCopies.begin(); | |||
3812 | const auto *IElemInitRef = Data.FirstprivateInits.begin(); | |||
3813 | for (const Expr *E : Data.FirstprivateVars) { | |||
3814 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3815 | Privates.emplace_back( | |||
3816 | C.getDeclAlign(VD), | |||
3817 | PrivateHelpersTy( | |||
3818 | E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), | |||
3819 | cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))); | |||
3820 | ++I; | |||
3821 | ++IElemInitRef; | |||
3822 | } | |||
3823 | I = Data.LastprivateCopies.begin(); | |||
3824 | for (const Expr *E : Data.LastprivateVars) { | |||
3825 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); | |||
3826 | Privates.emplace_back( | |||
3827 | C.getDeclAlign(VD), | |||
3828 | PrivateHelpersTy(E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), | |||
3829 | /*PrivateElemInit=*/nullptr)); | |||
3830 | ++I; | |||
3831 | } | |||
3832 | for (const VarDecl *VD : Data.PrivateLocals) { | |||
3833 | if (isAllocatableDecl(VD)) | |||
3834 | Privates.emplace_back(CGM.getPointerAlign(), PrivateHelpersTy(VD)); | |||
3835 | else | |||
3836 | Privates.emplace_back(C.getDeclAlign(VD), PrivateHelpersTy(VD)); | |||
3837 | } | |||
3838 | llvm::stable_sort(Privates, | |||
3839 | [](const PrivateDataTy &L, const PrivateDataTy &R) { | |||
3840 | return L.first > R.first; | |||
3841 | }); | |||
3842 | QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); | |||
3843 | // Build type kmp_routine_entry_t (if not built yet). | |||
3844 | emitKmpRoutineEntryT(KmpInt32Ty); | |||
3845 | // Build type kmp_task_t (if not built yet). | |||
3846 | if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) { | |||
3847 | if (SavedKmpTaskloopTQTy.isNull()) { | |||
3848 | SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl( | |||
3849 | CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy)); | |||
3850 | } | |||
3851 | KmpTaskTQTy = SavedKmpTaskloopTQTy; | |||
3852 | } else { | |||
3853 | assert((D.getDirectiveKind() == OMPD_task ||(static_cast <bool> ((D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && "Expected taskloop, task or target directive") ? void (0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3856, __extension__ __PRETTY_FUNCTION__)) | |||
3854 | isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||(static_cast <bool> ((D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && "Expected taskloop, task or target directive") ? void (0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3856, __extension__ __PRETTY_FUNCTION__)) | |||
3855 | isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&(static_cast <bool> ((D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && "Expected taskloop, task or target directive") ? void (0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3856, __extension__ __PRETTY_FUNCTION__)) | |||
3856 | "Expected taskloop, task or target directive")(static_cast <bool> ((D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && "Expected taskloop, task or target directive") ? void (0) : __assert_fail ("(D.getDirectiveKind() == OMPD_task || isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && \"Expected taskloop, task or target directive\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 3856, __extension__ __PRETTY_FUNCTION__)); | |||
3857 | if (SavedKmpTaskTQTy.isNull()) { | |||
3858 | SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl( | |||
3859 | CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy)); | |||
3860 | } | |||
3861 | KmpTaskTQTy = SavedKmpTaskTQTy; | |||
3862 | } | |||
3863 | const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl()); | |||
3864 | // Build particular struct kmp_task_t for the given task. | |||
3865 | const RecordDecl *KmpTaskTWithPrivatesQTyRD = | |||
3866 | createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates); | |||
3867 | QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD); | |||
3868 | QualType KmpTaskTWithPrivatesPtrQTy = | |||
3869 | C.getPointerType(KmpTaskTWithPrivatesQTy); | |||
3870 | llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy); | |||
3871 | llvm::Type *KmpTaskTWithPrivatesPtrTy = | |||
3872 | KmpTaskTWithPrivatesTy->getPointerTo(); | |||
3873 | llvm::Value *KmpTaskTWithPrivatesTySize = | |||
3874 | CGF.getTypeSize(KmpTaskTWithPrivatesQTy); | |||
3875 | QualType SharedsPtrTy = C.getPointerType(SharedsTy); | |||
3876 | ||||
3877 | // Emit initial values for private copies (if any). | |||
3878 | llvm::Value *TaskPrivatesMap = nullptr; | |||
3879 | llvm::Type *TaskPrivatesMapTy = | |||
3880 | std::next(TaskFunction->arg_begin(), 3)->getType(); | |||
3881 | if (!Privates.empty()) { | |||
3882 | auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
3883 | TaskPrivatesMap = | |||
3884 | emitTaskPrivateMappingFunction(CGM, Loc, Data, FI->getType(), Privates); | |||
3885 | TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3886 | TaskPrivatesMap, TaskPrivatesMapTy); | |||
3887 | } else { | |||
3888 | TaskPrivatesMap = llvm::ConstantPointerNull::get( | |||
3889 | cast<llvm::PointerType>(TaskPrivatesMapTy)); | |||
3890 | } | |||
3891 | // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid, | |||
3892 | // kmp_task_t *tt); | |||
3893 | llvm::Function *TaskEntry = emitProxyTaskFunction( | |||
3894 | CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, | |||
3895 | KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction, | |||
3896 | TaskPrivatesMap); | |||
3897 | ||||
3898 | // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid, | |||
3899 | // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, | |||
3900 | // kmp_routine_entry_t *task_entry); | |||
3901 | // Task flags. Format is taken from | |||
3902 | // https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h, | |||
3903 | // description of kmp_tasking_flags struct. | |||
3904 | enum { | |||
3905 | TiedFlag = 0x1, | |||
3906 | FinalFlag = 0x2, | |||
3907 | DestructorsFlag = 0x8, | |||
3908 | PriorityFlag = 0x20, | |||
3909 | DetachableFlag = 0x40, | |||
3910 | }; | |||
3911 | unsigned Flags = Data.Tied ? TiedFlag : 0; | |||
3912 | bool NeedsCleanup = false; | |||
3913 | if (!Privates.empty()) { | |||
3914 | NeedsCleanup = | |||
3915 | checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD, Privates); | |||
3916 | if (NeedsCleanup) | |||
3917 | Flags = Flags | DestructorsFlag; | |||
3918 | } | |||
3919 | if (Data.Priority.getInt()) | |||
3920 | Flags = Flags | PriorityFlag; | |||
3921 | if (D.hasClausesOfKind<OMPDetachClause>()) | |||
3922 | Flags = Flags | DetachableFlag; | |||
3923 | llvm::Value *TaskFlags = | |||
3924 | Data.Final.getPointer() | |||
3925 | ? CGF.Builder.CreateSelect(Data.Final.getPointer(), | |||
3926 | CGF.Builder.getInt32(FinalFlag), | |||
3927 | CGF.Builder.getInt32(/*C=*/0)) | |||
3928 | : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0); | |||
3929 | TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags)); | |||
3930 | llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy)); | |||
3931 | SmallVector<llvm::Value *, 8> AllocArgs = {emitUpdateLocation(CGF, Loc), | |||
3932 | getThreadID(CGF, Loc), TaskFlags, KmpTaskTWithPrivatesTySize, | |||
3933 | SharedsSize, CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
3934 | TaskEntry, KmpRoutineEntryPtrTy)}; | |||
3935 | llvm::Value *NewTask; | |||
3936 | if (D.hasClausesOfKind<OMPNowaitClause>()) { | |||
3937 | // Check if we have any device clause associated with the directive. | |||
3938 | const Expr *Device = nullptr; | |||
3939 | if (auto *C = D.getSingleClause<OMPDeviceClause>()) | |||
3940 | Device = C->getDevice(); | |||
3941 | // Emit device ID if any otherwise use default value. | |||
3942 | llvm::Value *DeviceID; | |||
3943 | if (Device) | |||
3944 | DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), | |||
3945 | CGF.Int64Ty, /*isSigned=*/true); | |||
3946 | else | |||
3947 | DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); | |||
3948 | AllocArgs.push_back(DeviceID); | |||
3949 | NewTask = CGF.EmitRuntimeCall( | |||
3950 | OMPBuilder.getOrCreateRuntimeFunction( | |||
3951 | CGM.getModule(), OMPRTL___kmpc_omp_target_task_alloc), | |||
3952 | AllocArgs); | |||
3953 | } else { | |||
3954 | NewTask = | |||
3955 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
3956 | CGM.getModule(), OMPRTL___kmpc_omp_task_alloc), | |||
3957 | AllocArgs); | |||
3958 | } | |||
3959 | // Emit detach clause initialization. | |||
3960 | // evt = (typeof(evt))__kmpc_task_allow_completion_event(loc, tid, | |||
3961 | // task_descriptor); | |||
3962 | if (const auto *DC = D.getSingleClause<OMPDetachClause>()) { | |||
3963 | const Expr *Evt = DC->getEventHandler()->IgnoreParenImpCasts(); | |||
3964 | LValue EvtLVal = CGF.EmitLValue(Evt); | |||
3965 | ||||
3966 | // Build kmp_event_t *__kmpc_task_allow_completion_event(ident_t *loc_ref, | |||
3967 | // int gtid, kmp_task_t *task); | |||
3968 | llvm::Value *Loc = emitUpdateLocation(CGF, DC->getBeginLoc()); | |||
3969 | llvm::Value *Tid = getThreadID(CGF, DC->getBeginLoc()); | |||
3970 | Tid = CGF.Builder.CreateIntCast(Tid, CGF.IntTy, /*isSigned=*/false); | |||
3971 | llvm::Value *EvtVal = CGF.EmitRuntimeCall( | |||
3972 | OMPBuilder.getOrCreateRuntimeFunction( | |||
3973 | CGM.getModule(), OMPRTL___kmpc_task_allow_completion_event), | |||
3974 | {Loc, Tid, NewTask}); | |||
3975 | EvtVal = CGF.EmitScalarConversion(EvtVal, C.VoidPtrTy, Evt->getType(), | |||
3976 | Evt->getExprLoc()); | |||
3977 | CGF.EmitStoreOfScalar(EvtVal, EvtLVal); | |||
3978 | } | |||
3979 | // Process affinity clauses. | |||
3980 | if (D.hasClausesOfKind<OMPAffinityClause>()) { | |||
3981 | // Process list of affinity data. | |||
3982 | ASTContext &C = CGM.getContext(); | |||
3983 | Address AffinitiesArray = Address::invalid(); | |||
3984 | // Calculate number of elements to form the array of affinity data. | |||
3985 | llvm::Value *NumOfElements = nullptr; | |||
3986 | unsigned NumAffinities = 0; | |||
3987 | for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) { | |||
3988 | if (const Expr *Modifier = C->getModifier()) { | |||
3989 | const auto *IE = cast<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts()); | |||
3990 | for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) { | |||
3991 | llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper); | |||
3992 | Sz = CGF.Builder.CreateIntCast(Sz, CGF.SizeTy, /*isSigned=*/false); | |||
3993 | NumOfElements = | |||
3994 | NumOfElements ? CGF.Builder.CreateNUWMul(NumOfElements, Sz) : Sz; | |||
3995 | } | |||
3996 | } else { | |||
3997 | NumAffinities += C->varlist_size(); | |||
3998 | } | |||
3999 | } | |||
4000 | getKmpAffinityType(CGM.getContext(), KmpTaskAffinityInfoTy); | |||
4001 | // Fields ids in kmp_task_affinity_info record. | |||
4002 | enum RTLAffinityInfoFieldsTy { BaseAddr, Len, Flags }; | |||
4003 | ||||
4004 | QualType KmpTaskAffinityInfoArrayTy; | |||
4005 | if (NumOfElements) { | |||
4006 | NumOfElements = CGF.Builder.CreateNUWAdd( | |||
4007 | llvm::ConstantInt::get(CGF.SizeTy, NumAffinities), NumOfElements); | |||
4008 | auto *OVE = new (C) OpaqueValueExpr( | |||
4009 | Loc, | |||
4010 | C.getIntTypeForBitwidth(C.getTypeSize(C.getSizeType()), /*Signed=*/0), | |||
4011 | VK_PRValue); | |||
4012 | CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE, | |||
4013 | RValue::get(NumOfElements)); | |||
4014 | KmpTaskAffinityInfoArrayTy = | |||
4015 | C.getVariableArrayType(KmpTaskAffinityInfoTy, OVE, ArrayType::Normal, | |||
4016 | /*IndexTypeQuals=*/0, SourceRange(Loc, Loc)); | |||
4017 | // Properly emit variable-sized array. | |||
4018 | auto *PD = ImplicitParamDecl::Create(C, KmpTaskAffinityInfoArrayTy, | |||
4019 | ImplicitParamDecl::Other); | |||
4020 | CGF.EmitVarDecl(*PD); | |||
4021 | AffinitiesArray = CGF.GetAddrOfLocalVar(PD); | |||
4022 | NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty, | |||
4023 | /*isSigned=*/false); | |||
4024 | } else { | |||
4025 | KmpTaskAffinityInfoArrayTy = C.getConstantArrayType( | |||
4026 | KmpTaskAffinityInfoTy, | |||
4027 | llvm::APInt(C.getTypeSize(C.getSizeType()), NumAffinities), nullptr, | |||
4028 | ArrayType::Normal, /*IndexTypeQuals=*/0); | |||
4029 | AffinitiesArray = | |||
4030 | CGF.CreateMemTemp(KmpTaskAffinityInfoArrayTy, ".affs.arr.addr"); | |||
4031 | AffinitiesArray = CGF.Builder.CreateConstArrayGEP(AffinitiesArray, 0); | |||
4032 | NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumAffinities, | |||
4033 | /*isSigned=*/false); | |||
4034 | } | |||
4035 | ||||
4036 | const auto *KmpAffinityInfoRD = KmpTaskAffinityInfoTy->getAsRecordDecl(); | |||
4037 | // Fill array by elements without iterators. | |||
4038 | unsigned Pos = 0; | |||
4039 | bool HasIterator = false; | |||
4040 | for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) { | |||
4041 | if (C->getModifier()) { | |||
4042 | HasIterator = true; | |||
4043 | continue; | |||
4044 | } | |||
4045 | for (const Expr *E : C->varlists()) { | |||
4046 | llvm::Value *Addr; | |||
4047 | llvm::Value *Size; | |||
4048 | std::tie(Addr, Size) = getPointerAndSize(CGF, E); | |||
4049 | LValue Base = | |||
4050 | CGF.MakeAddrLValue(CGF.Builder.CreateConstGEP(AffinitiesArray, Pos), | |||
4051 | KmpTaskAffinityInfoTy); | |||
4052 | // affs[i].base_addr = &<Affinities[i].second>; | |||
4053 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4054 | Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr)); | |||
4055 | CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy), | |||
4056 | BaseAddrLVal); | |||
4057 | // affs[i].len = sizeof(<Affinities[i].second>); | |||
4058 | LValue LenLVal = CGF.EmitLValueForField( | |||
4059 | Base, *std::next(KmpAffinityInfoRD->field_begin(), Len)); | |||
4060 | CGF.EmitStoreOfScalar(Size, LenLVal); | |||
4061 | ++Pos; | |||
4062 | } | |||
4063 | } | |||
4064 | LValue PosLVal; | |||
4065 | if (HasIterator) { | |||
4066 | PosLVal = CGF.MakeAddrLValue( | |||
4067 | CGF.CreateMemTemp(C.getSizeType(), "affs.counter.addr"), | |||
4068 | C.getSizeType()); | |||
4069 | CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal); | |||
4070 | } | |||
4071 | // Process elements with iterators. | |||
4072 | for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) { | |||
4073 | const Expr *Modifier = C->getModifier(); | |||
4074 | if (!Modifier) | |||
4075 | continue; | |||
4076 | OMPIteratorGeneratorScope IteratorScope( | |||
4077 | CGF, cast_or_null<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts())); | |||
4078 | for (const Expr *E : C->varlists()) { | |||
4079 | llvm::Value *Addr; | |||
4080 | llvm::Value *Size; | |||
4081 | std::tie(Addr, Size) = getPointerAndSize(CGF, E); | |||
4082 | llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc()); | |||
4083 | LValue Base = CGF.MakeAddrLValue( | |||
4084 | CGF.Builder.CreateGEP(AffinitiesArray, Idx), KmpTaskAffinityInfoTy); | |||
4085 | // affs[i].base_addr = &<Affinities[i].second>; | |||
4086 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4087 | Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr)); | |||
4088 | CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy), | |||
4089 | BaseAddrLVal); | |||
4090 | // affs[i].len = sizeof(<Affinities[i].second>); | |||
4091 | LValue LenLVal = CGF.EmitLValueForField( | |||
4092 | Base, *std::next(KmpAffinityInfoRD->field_begin(), Len)); | |||
4093 | CGF.EmitStoreOfScalar(Size, LenLVal); | |||
4094 | Idx = CGF.Builder.CreateNUWAdd( | |||
4095 | Idx, llvm::ConstantInt::get(Idx->getType(), 1)); | |||
4096 | CGF.EmitStoreOfScalar(Idx, PosLVal); | |||
4097 | } | |||
4098 | } | |||
4099 | // Call to kmp_int32 __kmpc_omp_reg_task_with_affinity(ident_t *loc_ref, | |||
4100 | // kmp_int32 gtid, kmp_task_t *new_task, kmp_int32 | |||
4101 | // naffins, kmp_task_affinity_info_t *affin_list); | |||
4102 | llvm::Value *LocRef = emitUpdateLocation(CGF, Loc); | |||
4103 | llvm::Value *GTid = getThreadID(CGF, Loc); | |||
4104 | llvm::Value *AffinListPtr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4105 | AffinitiesArray.getPointer(), CGM.VoidPtrTy); | |||
4106 | // FIXME: Emit the function and ignore its result for now unless the | |||
4107 | // runtime function is properly implemented. | |||
4108 | (void)CGF.EmitRuntimeCall( | |||
4109 | OMPBuilder.getOrCreateRuntimeFunction( | |||
4110 | CGM.getModule(), OMPRTL___kmpc_omp_reg_task_with_affinity), | |||
4111 | {LocRef, GTid, NewTask, NumOfElements, AffinListPtr}); | |||
4112 | } | |||
4113 | llvm::Value *NewTaskNewTaskTTy = | |||
4114 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4115 | NewTask, KmpTaskTWithPrivatesPtrTy); | |||
4116 | LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy, | |||
4117 | KmpTaskTWithPrivatesQTy); | |||
4118 | LValue TDBase = | |||
4119 | CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin()); | |||
4120 | // Fill the data in the resulting kmp_task_t record. | |||
4121 | // Copy shareds if there are any. | |||
4122 | Address KmpTaskSharedsPtr = Address::invalid(); | |||
4123 | if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) { | |||
4124 | KmpTaskSharedsPtr = Address( | |||
4125 | CGF.EmitLoadOfScalar( | |||
4126 | CGF.EmitLValueForField( | |||
4127 | TDBase, | |||
4128 | *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)), | |||
4129 | Loc), | |||
4130 | CGF.Int8Ty, CGM.getNaturalTypeAlignment(SharedsTy)); | |||
4131 | LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy); | |||
4132 | LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy); | |||
4133 | CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap); | |||
4134 | } | |||
4135 | // Emit initial values for private copies (if any). | |||
4136 | TaskResultTy Result; | |||
4137 | if (!Privates.empty()) { | |||
4138 | emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD, | |||
4139 | SharedsTy, SharedsPtrTy, Data, Privates, | |||
4140 | /*ForDup=*/false); | |||
4141 | if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) && | |||
4142 | (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) { | |||
4143 | Result.TaskDupFn = emitTaskDupFunction( | |||
4144 | CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD, | |||
4145 | KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates, | |||
4146 | /*WithLastIter=*/!Data.LastprivateVars.empty()); | |||
4147 | } | |||
4148 | } | |||
4149 | // Fields of union "kmp_cmplrdata_t" for destructors and priority. | |||
4150 | enum { Priority = 0, Destructors = 1 }; | |||
4151 | // Provide pointer to function with destructors for privates. | |||
4152 | auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1); | |||
4153 | const RecordDecl *KmpCmplrdataUD = | |||
4154 | (*FI)->getType()->getAsUnionType()->getDecl(); | |||
4155 | if (NeedsCleanup) { | |||
4156 | llvm::Value *DestructorFn = emitDestructorsFunction( | |||
4157 | CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, | |||
4158 | KmpTaskTWithPrivatesQTy); | |||
4159 | LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI); | |||
4160 | LValue DestructorsLV = CGF.EmitLValueForField( | |||
4161 | Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors)); | |||
4162 | CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4163 | DestructorFn, KmpRoutineEntryPtrTy), | |||
4164 | DestructorsLV); | |||
4165 | } | |||
4166 | // Set priority. | |||
4167 | if (Data.Priority.getInt()) { | |||
4168 | LValue Data2LV = CGF.EmitLValueForField( | |||
4169 | TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2)); | |||
4170 | LValue PriorityLV = CGF.EmitLValueForField( | |||
4171 | Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority)); | |||
4172 | CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV); | |||
4173 | } | |||
4174 | Result.NewTask = NewTask; | |||
4175 | Result.TaskEntry = TaskEntry; | |||
4176 | Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy; | |||
4177 | Result.TDBase = TDBase; | |||
4178 | Result.KmpTaskTQTyRD = KmpTaskTQTyRD; | |||
4179 | return Result; | |||
4180 | } | |||
4181 | ||||
4182 | /// Translates internal dependency kind into the runtime kind. | |||
4183 | static RTLDependenceKindTy translateDependencyKind(OpenMPDependClauseKind K) { | |||
4184 | RTLDependenceKindTy DepKind; | |||
4185 | switch (K) { | |||
4186 | case OMPC_DEPEND_in: | |||
4187 | DepKind = RTLDependenceKindTy::DepIn; | |||
4188 | break; | |||
4189 | // Out and InOut dependencies must use the same code. | |||
4190 | case OMPC_DEPEND_out: | |||
4191 | case OMPC_DEPEND_inout: | |||
4192 | DepKind = RTLDependenceKindTy::DepInOut; | |||
4193 | break; | |||
4194 | case OMPC_DEPEND_mutexinoutset: | |||
4195 | DepKind = RTLDependenceKindTy::DepMutexInOutSet; | |||
4196 | break; | |||
4197 | case OMPC_DEPEND_inoutset: | |||
4198 | DepKind = RTLDependenceKindTy::DepInOutSet; | |||
4199 | break; | |||
4200 | case OMPC_DEPEND_outallmemory: | |||
4201 | DepKind = RTLDependenceKindTy::DepOmpAllMem; | |||
4202 | break; | |||
4203 | case OMPC_DEPEND_source: | |||
4204 | case OMPC_DEPEND_sink: | |||
4205 | case OMPC_DEPEND_depobj: | |||
4206 | case OMPC_DEPEND_inoutallmemory: | |||
4207 | case OMPC_DEPEND_unknown: | |||
4208 | llvm_unreachable("Unknown task dependence type")::llvm::llvm_unreachable_internal("Unknown task dependence type" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4208); | |||
4209 | } | |||
4210 | return DepKind; | |||
4211 | } | |||
4212 | ||||
4213 | /// Builds kmp_depend_info, if it is not built yet, and builds flags type. | |||
4214 | static void getDependTypes(ASTContext &C, QualType &KmpDependInfoTy, | |||
4215 | QualType &FlagsTy) { | |||
4216 | FlagsTy = C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false); | |||
4217 | if (KmpDependInfoTy.isNull()) { | |||
4218 | RecordDecl *KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info"); | |||
4219 | KmpDependInfoRD->startDefinition(); | |||
4220 | addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType()); | |||
4221 | addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType()); | |||
4222 | addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy); | |||
4223 | KmpDependInfoRD->completeDefinition(); | |||
4224 | KmpDependInfoTy = C.getRecordType(KmpDependInfoRD); | |||
4225 | } | |||
4226 | } | |||
4227 | ||||
4228 | std::pair<llvm::Value *, LValue> | |||
4229 | CGOpenMPRuntime::getDepobjElements(CodeGenFunction &CGF, LValue DepobjLVal, | |||
4230 | SourceLocation Loc) { | |||
4231 | ASTContext &C = CGM.getContext(); | |||
4232 | QualType FlagsTy; | |||
4233 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4234 | RecordDecl *KmpDependInfoRD = | |||
4235 | cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); | |||
4236 | QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy); | |||
4237 | LValue Base = CGF.EmitLoadOfPointerLValue( | |||
4238 | CGF.Builder.CreateElementBitCast( | |||
4239 | DepobjLVal.getAddress(CGF), | |||
4240 | CGF.ConvertTypeForMem(KmpDependInfoPtrTy)), | |||
4241 | KmpDependInfoPtrTy->castAs<PointerType>()); | |||
4242 | Address DepObjAddr = CGF.Builder.CreateGEP( | |||
4243 | Base.getAddress(CGF), | |||
4244 | llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true)); | |||
4245 | LValue NumDepsBase = CGF.MakeAddrLValue( | |||
4246 | DepObjAddr, KmpDependInfoTy, Base.getBaseInfo(), Base.getTBAAInfo()); | |||
4247 | // NumDeps = deps[i].base_addr; | |||
4248 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4249 | NumDepsBase, | |||
4250 | *std::next(KmpDependInfoRD->field_begin(), | |||
4251 | static_cast<unsigned int>(RTLDependInfoFields::BaseAddr))); | |||
4252 | llvm::Value *NumDeps = CGF.EmitLoadOfScalar(BaseAddrLVal, Loc); | |||
4253 | return std::make_pair(NumDeps, Base); | |||
4254 | } | |||
4255 | ||||
4256 | static void emitDependData(CodeGenFunction &CGF, QualType &KmpDependInfoTy, | |||
4257 | llvm::PointerUnion<unsigned *, LValue *> Pos, | |||
4258 | const OMPTaskDataTy::DependData &Data, | |||
4259 | Address DependenciesArray) { | |||
4260 | CodeGenModule &CGM = CGF.CGM; | |||
4261 | ASTContext &C = CGM.getContext(); | |||
4262 | QualType FlagsTy; | |||
4263 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4264 | RecordDecl *KmpDependInfoRD = | |||
4265 | cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); | |||
4266 | llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy); | |||
4267 | ||||
4268 | OMPIteratorGeneratorScope IteratorScope( | |||
4269 | CGF, cast_or_null<OMPIteratorExpr>( | |||
4270 | Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts() | |||
4271 | : nullptr)); | |||
4272 | for (const Expr *E : Data.DepExprs) { | |||
4273 | llvm::Value *Addr; | |||
4274 | llvm::Value *Size; | |||
4275 | ||||
4276 | // The expression will be a nullptr in the 'omp_all_memory' case. | |||
4277 | if (E) { | |||
4278 | std::tie(Addr, Size) = getPointerAndSize(CGF, E); | |||
4279 | Addr = CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy); | |||
4280 | } else { | |||
4281 | Addr = llvm::ConstantInt::get(CGF.IntPtrTy, 0); | |||
4282 | Size = llvm::ConstantInt::get(CGF.SizeTy, 0); | |||
4283 | } | |||
4284 | LValue Base; | |||
4285 | if (unsigned *P = Pos.dyn_cast<unsigned *>()) { | |||
4286 | Base = CGF.MakeAddrLValue( | |||
4287 | CGF.Builder.CreateConstGEP(DependenciesArray, *P), KmpDependInfoTy); | |||
4288 | } else { | |||
4289 | assert(E && "Expected a non-null expression")(static_cast <bool> (E && "Expected a non-null expression" ) ? void (0) : __assert_fail ("E && \"Expected a non-null expression\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4289, __extension__ __PRETTY_FUNCTION__)); | |||
4290 | LValue &PosLVal = *Pos.get<LValue *>(); | |||
4291 | llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc()); | |||
4292 | Base = CGF.MakeAddrLValue( | |||
4293 | CGF.Builder.CreateGEP(DependenciesArray, Idx), KmpDependInfoTy); | |||
4294 | } | |||
4295 | // deps[i].base_addr = &<Dependencies[i].second>; | |||
4296 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4297 | Base, | |||
4298 | *std::next(KmpDependInfoRD->field_begin(), | |||
4299 | static_cast<unsigned int>(RTLDependInfoFields::BaseAddr))); | |||
4300 | CGF.EmitStoreOfScalar(Addr, BaseAddrLVal); | |||
4301 | // deps[i].len = sizeof(<Dependencies[i].second>); | |||
4302 | LValue LenLVal = CGF.EmitLValueForField( | |||
4303 | Base, *std::next(KmpDependInfoRD->field_begin(), | |||
4304 | static_cast<unsigned int>(RTLDependInfoFields::Len))); | |||
4305 | CGF.EmitStoreOfScalar(Size, LenLVal); | |||
4306 | // deps[i].flags = <Dependencies[i].first>; | |||
4307 | RTLDependenceKindTy DepKind = translateDependencyKind(Data.DepKind); | |||
4308 | LValue FlagsLVal = CGF.EmitLValueForField( | |||
4309 | Base, | |||
4310 | *std::next(KmpDependInfoRD->field_begin(), | |||
4311 | static_cast<unsigned int>(RTLDependInfoFields::Flags))); | |||
4312 | CGF.EmitStoreOfScalar( | |||
4313 | llvm::ConstantInt::get(LLVMFlagsTy, static_cast<unsigned int>(DepKind)), | |||
4314 | FlagsLVal); | |||
4315 | if (unsigned *P = Pos.dyn_cast<unsigned *>()) { | |||
4316 | ++(*P); | |||
4317 | } else { | |||
4318 | LValue &PosLVal = *Pos.get<LValue *>(); | |||
4319 | llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc()); | |||
4320 | Idx = CGF.Builder.CreateNUWAdd(Idx, | |||
4321 | llvm::ConstantInt::get(Idx->getType(), 1)); | |||
4322 | CGF.EmitStoreOfScalar(Idx, PosLVal); | |||
4323 | } | |||
4324 | } | |||
4325 | } | |||
4326 | ||||
4327 | SmallVector<llvm::Value *, 4> CGOpenMPRuntime::emitDepobjElementsSizes( | |||
4328 | CodeGenFunction &CGF, QualType &KmpDependInfoTy, | |||
4329 | const OMPTaskDataTy::DependData &Data) { | |||
4330 | assert(Data.DepKind == OMPC_DEPEND_depobj &&(static_cast <bool> (Data.DepKind == OMPC_DEPEND_depobj && "Expected depobj dependency kind.") ? void (0) : __assert_fail ("Data.DepKind == OMPC_DEPEND_depobj && \"Expected depobj dependency kind.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4331, __extension__ __PRETTY_FUNCTION__)) | |||
4331 | "Expected depobj dependency kind.")(static_cast <bool> (Data.DepKind == OMPC_DEPEND_depobj && "Expected depobj dependency kind.") ? void (0) : __assert_fail ("Data.DepKind == OMPC_DEPEND_depobj && \"Expected depobj dependency kind.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4331, __extension__ __PRETTY_FUNCTION__)); | |||
4332 | SmallVector<llvm::Value *, 4> Sizes; | |||
4333 | SmallVector<LValue, 4> SizeLVals; | |||
4334 | ASTContext &C = CGF.getContext(); | |||
4335 | { | |||
4336 | OMPIteratorGeneratorScope IteratorScope( | |||
4337 | CGF, cast_or_null<OMPIteratorExpr>( | |||
4338 | Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts() | |||
4339 | : nullptr)); | |||
4340 | for (const Expr *E : Data.DepExprs) { | |||
4341 | llvm::Value *NumDeps; | |||
4342 | LValue Base; | |||
4343 | LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts()); | |||
4344 | std::tie(NumDeps, Base) = | |||
4345 | getDepobjElements(CGF, DepobjLVal, E->getExprLoc()); | |||
4346 | LValue NumLVal = CGF.MakeAddrLValue( | |||
4347 | CGF.CreateMemTemp(C.getUIntPtrType(), "depobj.size.addr"), | |||
4348 | C.getUIntPtrType()); | |||
4349 | CGF.Builder.CreateStore(llvm::ConstantInt::get(CGF.IntPtrTy, 0), | |||
4350 | NumLVal.getAddress(CGF)); | |||
4351 | llvm::Value *PrevVal = CGF.EmitLoadOfScalar(NumLVal, E->getExprLoc()); | |||
4352 | llvm::Value *Add = CGF.Builder.CreateNUWAdd(PrevVal, NumDeps); | |||
4353 | CGF.EmitStoreOfScalar(Add, NumLVal); | |||
4354 | SizeLVals.push_back(NumLVal); | |||
4355 | } | |||
4356 | } | |||
4357 | for (unsigned I = 0, E = SizeLVals.size(); I < E; ++I) { | |||
4358 | llvm::Value *Size = | |||
4359 | CGF.EmitLoadOfScalar(SizeLVals[I], Data.DepExprs[I]->getExprLoc()); | |||
4360 | Sizes.push_back(Size); | |||
4361 | } | |||
4362 | return Sizes; | |||
4363 | } | |||
4364 | ||||
4365 | void CGOpenMPRuntime::emitDepobjElements(CodeGenFunction &CGF, | |||
4366 | QualType &KmpDependInfoTy, | |||
4367 | LValue PosLVal, | |||
4368 | const OMPTaskDataTy::DependData &Data, | |||
4369 | Address DependenciesArray) { | |||
4370 | assert(Data.DepKind == OMPC_DEPEND_depobj &&(static_cast <bool> (Data.DepKind == OMPC_DEPEND_depobj && "Expected depobj dependency kind.") ? void (0) : __assert_fail ("Data.DepKind == OMPC_DEPEND_depobj && \"Expected depobj dependency kind.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4371, __extension__ __PRETTY_FUNCTION__)) | |||
4371 | "Expected depobj dependency kind.")(static_cast <bool> (Data.DepKind == OMPC_DEPEND_depobj && "Expected depobj dependency kind.") ? void (0) : __assert_fail ("Data.DepKind == OMPC_DEPEND_depobj && \"Expected depobj dependency kind.\"" , "clang/lib/CodeGen/CGOpenMPRuntime.cpp", 4371, __extension__ __PRETTY_FUNCTION__)); | |||
4372 | llvm::Value *ElSize = CGF.getTypeSize(KmpDependInfoTy); | |||
4373 | { | |||
4374 | OMPIteratorGeneratorScope IteratorScope( | |||
4375 | CGF, cast_or_null<OMPIteratorExpr>( | |||
4376 | Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts() | |||
4377 | : nullptr)); | |||
4378 | for (unsigned I = 0, End = Data.DepExprs.size(); I < End; ++I) { | |||
4379 | const Expr *E = Data.DepExprs[I]; | |||
4380 | llvm::Value *NumDeps; | |||
4381 | LValue Base; | |||
4382 | LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts()); | |||
4383 | std::tie(NumDeps, Base) = | |||
4384 | getDepobjElements(CGF, DepobjLVal, E->getExprLoc()); | |||
4385 | ||||
4386 | // memcopy dependency data. | |||
4387 | llvm::Value *Size = CGF.Builder.CreateNUWMul( | |||
4388 | ElSize, | |||
4389 | CGF.Builder.CreateIntCast(NumDeps, CGF.SizeTy, /*isSigned=*/false)); | |||
4390 | llvm::Value *Pos = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc()); | |||
4391 | Address DepAddr = CGF.Builder.CreateGEP(DependenciesArray, Pos); | |||
4392 | CGF.Builder.CreateMemCpy(DepAddr, Base.getAddress(CGF), Size); | |||
4393 | ||||
4394 | // Increase pos. | |||
4395 | // pos += size; | |||
4396 | llvm::Value *Add = CGF.Builder.CreateNUWAdd(Pos, NumDeps); | |||
4397 | CGF.EmitStoreOfScalar(Add, PosLVal); | |||
4398 | } | |||
4399 | } | |||
4400 | } | |||
4401 | ||||
4402 | std::pair<llvm::Value *, Address> CGOpenMPRuntime::emitDependClause( | |||
4403 | CodeGenFunction &CGF, ArrayRef<OMPTaskDataTy::DependData> Dependencies, | |||
4404 | SourceLocation Loc) { | |||
4405 | if (llvm::all_of(Dependencies, [](const OMPTaskDataTy::DependData &D) { | |||
4406 | return D.DepExprs.empty(); | |||
4407 | })) | |||
4408 | return std::make_pair(nullptr, Address::invalid()); | |||
4409 | // Process list of dependencies. | |||
4410 | ASTContext &C = CGM.getContext(); | |||
4411 | Address DependenciesArray = Address::invalid(); | |||
4412 | llvm::Value *NumOfElements = nullptr; | |||
4413 | unsigned NumDependencies = std::accumulate( | |||
4414 | Dependencies.begin(), Dependencies.end(), 0, | |||
4415 | [](unsigned V, const OMPTaskDataTy::DependData &D) { | |||
4416 | return D.DepKind == OMPC_DEPEND_depobj | |||
4417 | ? V | |||
4418 | : (V + (D.IteratorExpr ? 0 : D.DepExprs.size())); | |||
4419 | }); | |||
4420 | QualType FlagsTy; | |||
4421 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4422 | bool HasDepobjDeps = false; | |||
4423 | bool HasRegularWithIterators = false; | |||
4424 | llvm::Value *NumOfDepobjElements = llvm::ConstantInt::get(CGF.IntPtrTy, 0); | |||
4425 | llvm::Value *NumOfRegularWithIterators = | |||
4426 | llvm::ConstantInt::get(CGF.IntPtrTy, 0); | |||
4427 | // Calculate number of depobj dependencies and regular deps with the | |||
4428 | // iterators. | |||
4429 | for (const OMPTaskDataTy::DependData &D : Dependencies) { | |||
4430 | if (D.DepKind == OMPC_DEPEND_depobj) { | |||
4431 | SmallVector<llvm::Value *, 4> Sizes = | |||
4432 | emitDepobjElementsSizes(CGF, KmpDependInfoTy, D); | |||
4433 | for (llvm::Value *Size : Sizes) { | |||
4434 | NumOfDepobjElements = | |||
4435 | CGF.Builder.CreateNUWAdd(NumOfDepobjElements, Size); | |||
4436 | } | |||
4437 | HasDepobjDeps = true; | |||
4438 | continue; | |||
4439 | } | |||
4440 | // Include number of iterations, if any. | |||
4441 | ||||
4442 | if (const auto *IE = cast_or_null<OMPIteratorExpr>(D.IteratorExpr)) { | |||
4443 | for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) { | |||
4444 | llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper); | |||
4445 | Sz = CGF.Builder.CreateIntCast(Sz, CGF.IntPtrTy, /*isSigned=*/false); | |||
4446 | llvm::Value *NumClauseDeps = CGF.Builder.CreateNUWMul( | |||
4447 | Sz, llvm::ConstantInt::get(CGF.IntPtrTy, D.DepExprs.size())); | |||
4448 | NumOfRegularWithIterators = | |||
4449 | CGF.Builder.CreateNUWAdd(NumOfRegularWithIterators, NumClauseDeps); | |||
4450 | } | |||
4451 | HasRegularWithIterators = true; | |||
4452 | continue; | |||
4453 | } | |||
4454 | } | |||
4455 | ||||
4456 | QualType KmpDependInfoArrayTy; | |||
4457 | if (HasDepobjDeps || HasRegularWithIterators) { | |||
4458 | NumOfElements = llvm::ConstantInt::get(CGM.IntPtrTy, NumDependencies, | |||
4459 | /*isSigned=*/false); | |||
4460 | if (HasDepobjDeps) { | |||
4461 | NumOfElements = | |||
4462 | CGF.Builder.CreateNUWAdd(NumOfDepobjElements, NumOfElements); | |||
4463 | } | |||
4464 | if (HasRegularWithIterators) { | |||
4465 | NumOfElements = | |||
4466 | CGF.Builder.CreateNUWAdd(NumOfRegularWithIterators, NumOfElements); | |||
4467 | } | |||
4468 | auto *OVE = new (C) OpaqueValueExpr( | |||
4469 | Loc, C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0), | |||
4470 | VK_PRValue); | |||
4471 | CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE, | |||
4472 | RValue::get(NumOfElements)); | |||
4473 | KmpDependInfoArrayTy = | |||
4474 | C.getVariableArrayType(KmpDependInfoTy, OVE, ArrayType::Normal, | |||
4475 | /*IndexTypeQuals=*/0, SourceRange(Loc, Loc)); | |||
4476 | // CGF.EmitVariablyModifiedType(KmpDependInfoArrayTy); | |||
4477 | // Properly emit variable-sized array. | |||
4478 | auto *PD = ImplicitParamDecl::Create(C, KmpDependInfoArrayTy, | |||
4479 | ImplicitParamDecl::Other); | |||
4480 | CGF.EmitVarDecl(*PD); | |||
4481 | DependenciesArray = CGF.GetAddrOfLocalVar(PD); | |||
4482 | NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty, | |||
4483 | /*isSigned=*/false); | |||
4484 | } else { | |||
4485 | KmpDependInfoArrayTy = C.getConstantArrayType( | |||
4486 | KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies), nullptr, | |||
4487 | ArrayType::Normal, /*IndexTypeQuals=*/0); | |||
4488 | DependenciesArray = | |||
4489 | CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr"); | |||
4490 | DependenciesArray = CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0); | |||
4491 | NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumDependencies, | |||
4492 | /*isSigned=*/false); | |||
4493 | } | |||
4494 | unsigned Pos = 0; | |||
4495 | for (unsigned I = 0, End = Dependencies.size(); I < End; ++I) { | |||
4496 | if (Dependencies[I].DepKind == OMPC_DEPEND_depobj || | |||
4497 | Dependencies[I].IteratorExpr) | |||
4498 | continue; | |||
4499 | emitDependData(CGF, KmpDependInfoTy, &Pos, Dependencies[I], | |||
4500 | DependenciesArray); | |||
4501 | } | |||
4502 | // Copy regular dependencies with iterators. | |||
4503 | LValue PosLVal = CGF.MakeAddrLValue( | |||
4504 | CGF.CreateMemTemp(C.getSizeType(), "dep.counter.addr"), C.getSizeType()); | |||
4505 | CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal); | |||
4506 | for (unsigned I = 0, End = Dependencies.size(); I < End; ++I) { | |||
4507 | if (Dependencies[I].DepKind == OMPC_DEPEND_depobj || | |||
4508 | !Dependencies[I].IteratorExpr) | |||
4509 | continue; | |||
4510 | emitDependData(CGF, KmpDependInfoTy, &PosLVal, Dependencies[I], | |||
4511 | DependenciesArray); | |||
4512 | } | |||
4513 | // Copy final depobj arrays without iterators. | |||
4514 | if (HasDepobjDeps) { | |||
4515 | for (unsigned I = 0, End = Dependencies.size(); I < End; ++I) { | |||
4516 | if (Dependencies[I].DepKind != OMPC_DEPEND_depobj) | |||
4517 | continue; | |||
4518 | emitDepobjElements(CGF, KmpDependInfoTy, PosLVal, Dependencies[I], | |||
4519 | DependenciesArray); | |||
4520 | } | |||
4521 | } | |||
4522 | DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4523 | DependenciesArray, CGF.VoidPtrTy, CGF.Int8Ty); | |||
4524 | return std::make_pair(NumOfElements, DependenciesArray); | |||
4525 | } | |||
4526 | ||||
4527 | Address CGOpenMPRuntime::emitDepobjDependClause( | |||
4528 | CodeGenFunction &CGF, const OMPTaskDataTy::DependData &Dependencies, | |||
4529 | SourceLocation Loc) { | |||
4530 | if (Dependencies.DepExprs.empty()) | |||
4531 | return Address::invalid(); | |||
4532 | // Process list of dependencies. | |||
4533 | ASTContext &C = CGM.getContext(); | |||
4534 | Address DependenciesArray = Address::invalid(); | |||
4535 | unsigned NumDependencies = Dependencies.DepExprs.size(); | |||
4536 | QualType FlagsTy; | |||
4537 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4538 | RecordDecl *KmpDependInfoRD = | |||
4539 | cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); | |||
4540 | ||||
4541 | llvm::Value *Size; | |||
4542 | // Define type kmp_depend_info[<Dependencies.size()>]; | |||
4543 | // For depobj reserve one extra element to store the number of elements. | |||
4544 | // It is required to handle depobj(x) update(in) construct. | |||
4545 | // kmp_depend_info[<Dependencies.size()>] deps; | |||
4546 | llvm::Value *NumDepsVal; | |||
4547 | CharUnits Align = C.getTypeAlignInChars(KmpDependInfoTy); | |||
4548 | if (const auto *IE = | |||
4549 | cast_or_null<OMPIteratorExpr>(Dependencies.IteratorExpr)) { | |||
4550 | NumDepsVal = llvm::ConstantInt::get(CGF.SizeTy, 1); | |||
4551 | for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) { | |||
4552 | llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper); | |||
4553 | Sz = CGF.Builder.CreateIntCast(Sz, CGF.SizeTy, /*isSigned=*/false); | |||
4554 | NumDepsVal = CGF.Builder.CreateNUWMul(NumDepsVal, Sz); | |||
4555 | } | |||
4556 | Size = CGF.Builder.CreateNUWAdd(llvm::ConstantInt::get(CGF.SizeTy, 1), | |||
4557 | NumDepsVal); | |||
4558 | CharUnits SizeInBytes = | |||
4559 | C.getTypeSizeInChars(KmpDependInfoTy).alignTo(Align); | |||
4560 | llvm::Value *RecSize = CGM.getSize(SizeInBytes); | |||
4561 | Size = CGF.Builder.CreateNUWMul(Size, RecSize); | |||
4562 | NumDepsVal = | |||
4563 | CGF.Builder.CreateIntCast(NumDepsVal, CGF.IntPtrTy, /*isSigned=*/false); | |||
4564 | } else { | |||
4565 | QualType KmpDependInfoArrayTy = C.getConstantArrayType( | |||
4566 | KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies + 1), | |||
4567 | nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0); | |||
4568 | CharUnits Sz = C.getTypeSizeInChars(KmpDependInfoArrayTy); | |||
4569 | Size = CGM.getSize(Sz.alignTo(Align)); | |||
4570 | NumDepsVal = llvm::ConstantInt::get(CGF.IntPtrTy, NumDependencies); | |||
4571 | } | |||
4572 | // Need to allocate on the dynamic memory. | |||
4573 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
4574 | // Use default allocator. | |||
4575 | llvm::Value *Allocator = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
4576 | llvm::Value *Args[] = {ThreadID, Size, Allocator}; | |||
4577 | ||||
4578 | llvm::Value *Addr = | |||
4579 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4580 | CGM.getModule(), OMPRTL___kmpc_alloc), | |||
4581 | Args, ".dep.arr.addr"); | |||
4582 | llvm::Type *KmpDependInfoLlvmTy = CGF.ConvertTypeForMem(KmpDependInfoTy); | |||
4583 | Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4584 | Addr, KmpDependInfoLlvmTy->getPointerTo()); | |||
4585 | DependenciesArray = Address(Addr, KmpDependInfoLlvmTy, Align); | |||
4586 | // Write number of elements in the first element of array for depobj. | |||
4587 | LValue Base = CGF.MakeAddrLValue(DependenciesArray, KmpDependInfoTy); | |||
4588 | // deps[i].base_addr = NumDependencies; | |||
4589 | LValue BaseAddrLVal = CGF.EmitLValueForField( | |||
4590 | Base, | |||
4591 | *std::next(KmpDependInfoRD->field_begin(), | |||
4592 | static_cast<unsigned int>(RTLDependInfoFields::BaseAddr))); | |||
4593 | CGF.EmitStoreOfScalar(NumDepsVal, BaseAddrLVal); | |||
4594 | llvm::PointerUnion<unsigned *, LValue *> Pos; | |||
4595 | unsigned Idx = 1; | |||
4596 | LValue PosLVal; | |||
4597 | if (Dependencies.IteratorExpr) { | |||
4598 | PosLVal = CGF.MakeAddrLValue( | |||
4599 | CGF.CreateMemTemp(C.getSizeType(), "iterator.counter.addr"), | |||
4600 | C.getSizeType()); | |||
4601 | CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Idx), PosLVal, | |||
4602 | /*IsInit=*/true); | |||
4603 | Pos = &PosLVal; | |||
4604 | } else { | |||
4605 | Pos = &Idx; | |||
4606 | } | |||
4607 | emitDependData(CGF, KmpDependInfoTy, Pos, Dependencies, DependenciesArray); | |||
4608 | DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4609 | CGF.Builder.CreateConstGEP(DependenciesArray, 1), CGF.VoidPtrTy, | |||
4610 | CGF.Int8Ty); | |||
4611 | return DependenciesArray; | |||
4612 | } | |||
4613 | ||||
4614 | void CGOpenMPRuntime::emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal, | |||
4615 | SourceLocation Loc) { | |||
4616 | ASTContext &C = CGM.getContext(); | |||
4617 | QualType FlagsTy; | |||
4618 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4619 | LValue Base = CGF.EmitLoadOfPointerLValue( | |||
4620 | DepobjLVal.getAddress(CGF), C.VoidPtrTy.castAs<PointerType>()); | |||
4621 | QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy); | |||
4622 | Address Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4623 | Base.getAddress(CGF), CGF.ConvertTypeForMem(KmpDependInfoPtrTy), | |||
4624 | CGF.ConvertTypeForMem(KmpDependInfoTy)); | |||
4625 | llvm::Value *DepObjAddr = CGF.Builder.CreateGEP( | |||
4626 | Addr.getElementType(), Addr.getPointer(), | |||
4627 | llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true)); | |||
4628 | DepObjAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(DepObjAddr, | |||
4629 | CGF.VoidPtrTy); | |||
4630 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
4631 | // Use default allocator. | |||
4632 | llvm::Value *Allocator = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
4633 | llvm::Value *Args[] = {ThreadID, DepObjAddr, Allocator}; | |||
4634 | ||||
4635 | // _kmpc_free(gtid, addr, nullptr); | |||
4636 | (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4637 | CGM.getModule(), OMPRTL___kmpc_free), | |||
4638 | Args); | |||
4639 | } | |||
4640 | ||||
4641 | void CGOpenMPRuntime::emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal, | |||
4642 | OpenMPDependClauseKind NewDepKind, | |||
4643 | SourceLocation Loc) { | |||
4644 | ASTContext &C = CGM.getContext(); | |||
4645 | QualType FlagsTy; | |||
4646 | getDependTypes(C, KmpDependInfoTy, FlagsTy); | |||
4647 | RecordDecl *KmpDependInfoRD = | |||
4648 | cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); | |||
4649 | llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy); | |||
4650 | llvm::Value *NumDeps; | |||
4651 | LValue Base; | |||
4652 | std::tie(NumDeps, Base) = getDepobjElements(CGF, DepobjLVal, Loc); | |||
4653 | ||||
4654 | Address Begin = Base.getAddress(CGF); | |||
4655 | // Cast from pointer to array type to pointer to single element. | |||
4656 | llvm::Value *End = CGF.Builder.CreateGEP( | |||
4657 | Begin.getElementType(), Begin.getPointer(), NumDeps); | |||
4658 | // The basic structure here is a while-do loop. | |||
4659 | llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.body"); | |||
4660 | llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.done"); | |||
4661 | llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); | |||
4662 | CGF.EmitBlock(BodyBB); | |||
4663 | llvm::PHINode *ElementPHI = | |||
4664 | CGF.Builder.CreatePHI(Begin.getType(), 2, "omp.elementPast"); | |||
4665 | ElementPHI->addIncoming(Begin.getPointer(), EntryBB); | |||
4666 | Begin = Begin.withPointer(ElementPHI, KnownNonNull); | |||
4667 | Base = CGF.MakeAddrLValue(Begin, KmpDependInfoTy, Base.getBaseInfo(), | |||
4668 | Base.getTBAAInfo()); | |||
4669 | // deps[i].flags = NewDepKind; | |||
4670 | RTLDependenceKindTy DepKind = translateDependencyKind(NewDepKind); | |||
4671 | LValue FlagsLVal = CGF.EmitLValueForField( | |||
4672 | Base, *std::next(KmpDependInfoRD->field_begin(), | |||
4673 | static_cast<unsigned int>(RTLDependInfoFields::Flags))); | |||
4674 | CGF.EmitStoreOfScalar( | |||
4675 | llvm::ConstantInt::get(LLVMFlagsTy, static_cast<unsigned int>(DepKind)), | |||
4676 | FlagsLVal); | |||
4677 | ||||
4678 | // Shift the address forward by one element. | |||
4679 | Address ElementNext = | |||
4680 | CGF.Builder.CreateConstGEP(Begin, /*Index=*/1, "omp.elementNext"); | |||
4681 | ElementPHI->addIncoming(ElementNext.getPointer(), | |||
4682 | CGF.Builder.GetInsertBlock()); | |||
4683 | llvm::Value *IsEmpty = | |||
4684 | CGF.Builder.CreateICmpEQ(ElementNext.getPointer(), End, "omp.isempty"); | |||
4685 | CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); | |||
4686 | // Done. | |||
4687 | CGF.EmitBlock(DoneBB, /*IsFinished=*/true); | |||
4688 | } | |||
4689 | ||||
4690 | void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
4691 | const OMPExecutableDirective &D, | |||
4692 | llvm::Function *TaskFunction, | |||
4693 | QualType SharedsTy, Address Shareds, | |||
4694 | const Expr *IfCond, | |||
4695 | const OMPTaskDataTy &Data) { | |||
4696 | if (!CGF.HaveInsertPoint()) | |||
4697 | return; | |||
4698 | ||||
4699 | TaskResultTy Result = | |||
4700 | emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data); | |||
4701 | llvm::Value *NewTask = Result.NewTask; | |||
4702 | llvm::Function *TaskEntry = Result.TaskEntry; | |||
4703 | llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy; | |||
4704 | LValue TDBase = Result.TDBase; | |||
4705 | const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD; | |||
4706 | // Process list of dependences. | |||
4707 | Address DependenciesArray = Address::invalid(); | |||
4708 | llvm::Value *NumOfElements; | |||
4709 | std::tie(NumOfElements, DependenciesArray) = | |||
4710 | emitDependClause(CGF, Data.Dependences, Loc); | |||
4711 | ||||
4712 | // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc() | |||
4713 | // libcall. | |||
4714 | // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid, | |||
4715 | // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list, | |||
4716 | // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence | |||
4717 | // list is not empty | |||
4718 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
4719 | llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc); | |||
4720 | llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask }; | |||
4721 | llvm::Value *DepTaskArgs[7]; | |||
4722 | if (!Data.Dependences.empty()) { | |||
4723 | DepTaskArgs[0] = UpLoc; | |||
4724 | DepTaskArgs[1] = ThreadID; | |||
4725 | DepTaskArgs[2] = NewTask; | |||
4726 | DepTaskArgs[3] = NumOfElements; | |||
4727 | DepTaskArgs[4] = DependenciesArray.getPointer(); | |||
4728 | DepTaskArgs[5] = CGF.Builder.getInt32(0); | |||
4729 | DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
4730 | } | |||
4731 | auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, &TaskArgs, | |||
4732 | &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) { | |||
4733 | if (!Data.Tied) { | |||
4734 | auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId); | |||
4735 | LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI); | |||
4736 | CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal); | |||
4737 | } | |||
4738 | if (!Data.Dependences.empty()) { | |||
4739 | CGF.EmitRuntimeCall( | |||
4740 | OMPBuilder.getOrCreateRuntimeFunction( | |||
4741 | CGM.getModule(), OMPRTL___kmpc_omp_task_with_deps), | |||
4742 | DepTaskArgs); | |||
4743 | } else { | |||
4744 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4745 | CGM.getModule(), OMPRTL___kmpc_omp_task), | |||
4746 | TaskArgs); | |||
4747 | } | |||
4748 | // Check if parent region is untied and build return for untied task; | |||
4749 | if (auto *Region = | |||
4750 | dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) | |||
4751 | Region->emitUntiedSwitch(CGF); | |||
4752 | }; | |||
4753 | ||||
4754 | llvm::Value *DepWaitTaskArgs[7]; | |||
4755 | if (!Data.Dependences.empty()) { | |||
4756 | DepWaitTaskArgs[0] = UpLoc; | |||
4757 | DepWaitTaskArgs[1] = ThreadID; | |||
4758 | DepWaitTaskArgs[2] = NumOfElements; | |||
4759 | DepWaitTaskArgs[3] = DependenciesArray.getPointer(); | |||
4760 | DepWaitTaskArgs[4] = CGF.Builder.getInt32(0); | |||
4761 | DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); | |||
4762 | DepWaitTaskArgs[6] = | |||
4763 | llvm::ConstantInt::get(CGF.Int32Ty, Data.HasNowaitClause); | |||
4764 | } | |||
4765 | auto &M = CGM.getModule(); | |||
4766 | auto &&ElseCodeGen = [this, &M, &TaskArgs, ThreadID, NewTaskNewTaskTTy, | |||
4767 | TaskEntry, &Data, &DepWaitTaskArgs, | |||
4768 | Loc](CodeGenFunction &CGF, PrePostActionTy &) { | |||
4769 | CodeGenFunction::RunCleanupsScope LocalScope(CGF); | |||
4770 | // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid, | |||
4771 | // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 | |||
4772 | // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info | |||
4773 | // is specified. | |||
4774 | if (!Data.Dependences.empty()) | |||
4775 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4776 | M, OMPRTL___kmpc_omp_taskwait_deps_51), | |||
4777 | DepWaitTaskArgs); | |||
4778 | // Call proxy_task_entry(gtid, new_task); | |||
4779 | auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy, | |||
4780 | Loc](CodeGenFunction &CGF, PrePostActionTy &Action) { | |||
4781 | Action.Enter(CGF); | |||
4782 | llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy}; | |||
4783 | CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry, | |||
4784 | OutlinedFnArgs); | |||
4785 | }; | |||
4786 | ||||
4787 | // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid, | |||
4788 | // kmp_task_t *new_task); | |||
4789 | // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid, | |||
4790 | // kmp_task_t *new_task); | |||
4791 | RegionCodeGenTy RCG(CodeGen); | |||
4792 | CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction( | |||
4793 | M, OMPRTL___kmpc_omp_task_begin_if0), | |||
4794 | TaskArgs, | |||
4795 | OMPBuilder.getOrCreateRuntimeFunction( | |||
4796 | M, OMPRTL___kmpc_omp_task_complete_if0), | |||
4797 | TaskArgs); | |||
4798 | RCG.setAction(Action); | |||
4799 | RCG(CGF); | |||
4800 | }; | |||
4801 | ||||
4802 | if (IfCond) { | |||
4803 | emitIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen); | |||
4804 | } else { | |||
4805 | RegionCodeGenTy ThenRCG(ThenCodeGen); | |||
4806 | ThenRCG(CGF); | |||
4807 | } | |||
4808 | } | |||
4809 | ||||
4810 | void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, | |||
4811 | const OMPLoopDirective &D, | |||
4812 | llvm::Function *TaskFunction, | |||
4813 | QualType SharedsTy, Address Shareds, | |||
4814 | const Expr *IfCond, | |||
4815 | const OMPTaskDataTy &Data) { | |||
4816 | if (!CGF.HaveInsertPoint()) | |||
4817 | return; | |||
4818 | TaskResultTy Result = | |||
4819 | emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data); | |||
4820 | // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc() | |||
4821 | // libcall. | |||
4822 | // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int | |||
4823 | // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int | |||
4824 | // sched, kmp_uint64 grainsize, void *task_dup); | |||
4825 | llvm::Value *ThreadID = getThreadID(CGF, Loc); | |||
4826 | llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc); | |||
4827 | llvm::Value *IfVal; | |||
4828 | if (IfCond) { | |||
4829 | IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy, | |||
4830 | /*isSigned=*/true); | |||
4831 | } else { | |||
4832 | IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1); | |||
4833 | } | |||
4834 | ||||
4835 | LValue LBLVal = CGF.EmitLValueForField( | |||
4836 | Result.TDBase, | |||
4837 | *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound)); | |||
4838 | const auto *LBVar = | |||
4839 | cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl()); | |||
4840 | CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(CGF), | |||
4841 | LBLVal.getQuals(), | |||
4842 | /*IsInitializer=*/true); | |||
4843 | LValue UBLVal = CGF.EmitLValueForField( | |||
4844 | Result.TDBase, | |||
4845 | *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound)); | |||
4846 | const auto *UBVar = | |||
4847 | cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl()); | |||
4848 | CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(CGF), | |||
4849 | UBLVal.getQuals(), | |||
4850 | /*IsInitializer=*/true); | |||
4851 | LValue StLVal = CGF.EmitLValueForField( | |||
4852 | Result.TDBase, | |||
4853 | *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride)); | |||
4854 | const auto *StVar = | |||
4855 | cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl()); | |||
4856 | CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(CGF), | |||
4857 | StLVal.getQuals(), | |||
4858 | /*IsInitializer=*/true); | |||
4859 | // Store reductions address. | |||
4860 | LValue RedLVal = CGF.EmitLValueForField( | |||
4861 | Result.TDBase, | |||
4862 | *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions)); | |||
4863 | if (Data.Reductions) { | |||
4864 | CGF.EmitStoreOfScalar(Data.Reductions, RedLVal); | |||
4865 | } else { | |||
4866 | CGF.EmitNullInitialization(RedLVal.getAddress(CGF), | |||
4867 | CGF.getContext().VoidPtrTy); | |||
4868 | } | |||
4869 | enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 }; | |||
4870 | llvm::Value *TaskArgs[] = { | |||
4871 | UpLoc, | |||
4872 | ThreadID, | |||
4873 | Result.NewTask, | |||
4874 | IfVal, | |||
4875 | LBLVal.getPointer(CGF), | |||
4876 | UBLVal.getPointer(CGF), | |||
4877 | CGF.EmitLoadOfScalar(StLVal, Loc), | |||
4878 | llvm::ConstantInt::getSigned( | |||
4879 | CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler | |||
4880 | llvm::ConstantInt::getSigned( | |||
4881 | CGF.IntTy, Data.Schedule.getPointer() | |||
4882 | ? Data.Schedule.getInt() ? NumTasks : Grainsize | |||
4883 | : NoSchedule), | |||
4884 | Data.Schedule.getPointer() | |||
4885 | ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty, | |||
4886 | /*isSigned=*/false) | |||
4887 | : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0), | |||
4888 | Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
4889 | Result.TaskDupFn, CGF.VoidPtrTy) | |||
4890 | : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)}; | |||
4891 | CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
4892 | CGM.getModule(), OMPRTL___kmpc_taskloop), | |||
4893 | TaskArgs); | |||
4894 | } | |||
4895 | ||||
4896 | /// Emit reduction operation for each element of array (required for | |||
4897 | /// array sections) LHS op = RHS. | |||
4898 | /// \param Type Type of array. | |||
4899 | /// \param LHSVar Variable on the left side of the reduction operation | |||
4900 | /// (references element of array in original variable). | |||
4901 | /// \param RHSVar Variable on the right side of the reduction operation | |||
4902 | /// (references element of array in original variable). | |||
4903 | /// \param RedOpGen Generator of reduction operation with use of LHSVar and | |||
4904 | /// RHSVar. | |||
4905 | static void EmitOMPAggregateReduction( | |||
4906 | CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar, | |||
4907 | const VarDecl *RHSVar, | |||
4908 | const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *, | |||
4909 | const Expr *, const Expr *)> &RedOpGen, | |||
4910 | const Expr *XExpr = nullptr, const Expr *EExpr = nullptr, | |||
4911 | const Expr *UpExpr = nullptr) { | |||
4912 | // Perform element-by-element initialization. | |||
4913 | QualType ElementTy; | |||
4914 | Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar); | |||
4915 | Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar); | |||
4916 | ||||
4917 | // Drill down to the base element type on both arrays. | |||
4918 | const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe(); | |||
4919 | llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr); | |||
4920 | ||||
4921 | llvm::Value *RHSBegin = RHSAddr.getPointer(); | |||
4922 | llvm::Value *LHSBegin = LHSAddr.getPointer(); | |||
4923 | // Cast from pointer to array type to pointer to single element. | |||
4924 | llvm::Value *LHSEnd = | |||
4925 | CGF.Builder.CreateGEP(LHSAddr.getElementType(), LHSBegin, NumElements); | |||
4926 | // The basic structure here is a while-do loop. | |||
4927 | llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body"); | |||
4928 | llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done"); | |||
4929 | llvm::Value *IsEmpty = | |||
4930 | CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty"); | |||
4931 | CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); | |||
4932 | ||||
4933 | // Enter the loop body, making that address the current address. | |||
4934 | llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); | |||
4935 | CGF.EmitBlock(BodyBB); | |||
4936 | ||||
4937 | CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy); | |||
4938 | ||||
4939 | llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI( | |||
4940 | RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast"); | |||
4941 | RHSElementPHI->addIncoming(RHSBegin, EntryBB); | |||
4942 | Address RHSElementCurrent( | |||
4943 | RHSElementPHI, RHSAddr.getElementType(), | |||
4944 | RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize)); | |||
4945 | ||||
4946 | llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI( | |||
4947 | LHSBegin->getType(), 2, "omp.arraycpy.destElementPast"); | |||
4948 | LHSElementPHI->addIncoming(LHSBegin, EntryBB); | |||
4949 | Address LHSElementCurrent( | |||
4950 | LHSElementPHI, LHSAddr.getElementType(), | |||
4951 | LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize)); | |||
4952 | ||||
4953 | // Emit copy. | |||
4954 | CodeGenFunction::OMPPrivateScope Scope(CGF); | |||
4955 | Scope.addPrivate(LHSVar, LHSElementCurrent); | |||
4956 | Scope.addPrivate(RHSVar, RHSElementCurrent); | |||
4957 | Scope.Privatize(); | |||
4958 | RedOpGen(CGF, XExpr, EExpr, UpExpr); | |||
4959 | Scope.ForceCleanup(); | |||
4960 | ||||
4961 | // Shift the address forward by one element. | |||
4962 | llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32( | |||
4963 | LHSAddr.getElementType(), LHSElementPHI, /*Idx0=*/1, | |||
4964 | "omp.arraycpy.dest.element"); | |||
4965 | llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32( | |||
4966 | RHSAddr.getElementType(), RHSElementPHI, /*Idx0=*/1, | |||
4967 | "omp.arraycpy.src.element"); | |||
4968 | // Check whether we've reached the end. | |||
4969 | llvm::Value *Done = | |||
4970 | CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done"); | |||
4971 | CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB); | |||
4972 | LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock()); | |||
4973 | RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock()); | |||
4974 | ||||
4975 | // Done. | |||
4976 | CGF.EmitBlock(DoneBB, /*IsFinished=*/true); | |||
4977 | } | |||
4978 | ||||
4979 | /// Emit reduction combiner. If the combiner is a simple expression emit it as | |||
4980 | /// is, otherwise consider it as combiner of UDR decl and emit it as a call of | |||
4981 | /// UDR combiner function. | |||
4982 | static void emitReductionCombiner(CodeGenFunction &CGF, | |||
4983 | const Expr *ReductionOp) { | |||
4984 | if (const auto *CE = dyn_cast<CallExpr>(ReductionOp)) | |||
4985 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee())) | |||
4986 | if (const auto *DRE = | |||
4987 | dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts())) | |||
4988 | if (const auto *DRD = | |||
4989 | dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) { | |||
4990 | std::pair<llvm::Function *, llvm::Function *> Reduction = | |||
4991 | CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD); | |||
4992 | RValue Func = RValue::get(Reduction.first); | |||
4993 | CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func); | |||
4994 | CGF.EmitIgnoredExpr(ReductionOp); | |||
4995 | return; | |||
4996 | } | |||
4997 | CGF.EmitIgnoredExpr(ReductionOp); | |||
4998 | } | |||
4999 | ||||
5000 | llvm::Function *CGOpenMPRuntime::emitReductionFunction( | |||
5001 | SourceLocation Loc, llvm::Type *ArgsElemType, | |||
5002 | ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, | |||
5003 | ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) { | |||
5004 | ASTContext &C = CGM.getContext(); | |||
5005 | ||||
5006 | // void reduction_func(void *LHSArg, void *RHSArg); | |||
5007 | FunctionArgList Args; | |||
5008 | ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
5009 | ImplicitParamDecl::Other); | |||
5010 | ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
5011 | ImplicitParamDecl::Other); | |||
5012 | Args.push_back(&LHSArg); | |||
5013 | Args.push_back(&RHSArg); | |||
5014 | const auto &CGFI = | |||
5015 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
5016 | std::string Name = getName({"omp", "reduction", "reduction_func"}); | |||
5017 | auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI), | |||
5018 | llvm::GlobalValue::InternalLinkage, Name, | |||
5019 | &CGM.getModule()); | |||
5020 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); | |||
5021 | Fn->setDoesNotRecurse(); | |||
5022 | CodeGenFunction CGF(CGM); | |||
5023 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); | |||
5024 | ||||
5025 | // Dst = (void*[n])(LHSArg); | |||
5026 | // Src = (void*[n])(RHSArg); | |||
5027 | Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5028 | CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)), | |||
5029 | ArgsElemType->getPointerTo()), | |||
5030 | ArgsElemType, CGF.getPointerAlign()); | |||
5031 | Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5032 | CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)), | |||
5033 | ArgsElemType->getPointerTo()), | |||
5034 | ArgsElemType, CGF.getPointerAlign()); | |||
5035 | ||||
5036 | // ... | |||
5037 | // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); | |||
5038 | // ... | |||
5039 | CodeGenFunction::OMPPrivateScope Scope(CGF); | |||
5040 | const auto *IPriv = Privates.begin(); | |||
5041 | unsigned Idx = 0; | |||
5042 | for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) { | |||
5043 | const auto *RHSVar = | |||
5044 | cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()); | |||
5045 | Scope.addPrivate(RHSVar, emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar)); | |||
5046 | const auto *LHSVar = | |||
5047 | cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()); | |||
5048 | Scope.addPrivate(LHSVar, emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar)); | |||
5049 | QualType PrivTy = (*IPriv)->getType(); | |||
5050 | if (PrivTy->isVariablyModifiedType()) { | |||
5051 | // Get array size and emit VLA type. | |||
5052 | ++Idx; | |||
5053 | Address Elem = CGF.Builder.CreateConstArrayGEP(LHS, Idx); | |||
5054 | llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem); | |||
5055 | const VariableArrayType *VLA = | |||
5056 | CGF.getContext().getAsVariableArrayType(PrivTy); | |||
5057 | const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr()); | |||
5058 | CodeGenFunction::OpaqueValueMapping OpaqueMap( | |||
5059 | CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy))); | |||
5060 | CGF.EmitVariablyModifiedType(PrivTy); | |||
5061 | } | |||
5062 | } | |||
5063 | Scope.Privatize(); | |||
5064 | IPriv = Privates.begin(); | |||
5065 | const auto *ILHS = LHSExprs.begin(); | |||
5066 | const auto *IRHS = RHSExprs.begin(); | |||
5067 | for (const Expr *E : ReductionOps) { | |||
5068 | if ((*IPriv)->getType()->isArrayType()) { | |||
5069 | // Emit reduction for array section. | |||
5070 | const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); | |||
5071 | const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); | |||
5072 | EmitOMPAggregateReduction( | |||
5073 | CGF, (*IPriv)->getType(), LHSVar, RHSVar, | |||
5074 | [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) { | |||
5075 | emitReductionCombiner(CGF, E); | |||
5076 | }); | |||
5077 | } else { | |||
5078 | // Emit reduction for array subscript or single variable. | |||
5079 | emitReductionCombiner(CGF, E); | |||
5080 | } | |||
5081 | ++IPriv; | |||
5082 | ++ILHS; | |||
5083 | ++IRHS; | |||
5084 | } | |||
5085 | Scope.ForceCleanup(); | |||
5086 | CGF.FinishFunction(); | |||
5087 | return Fn; | |||
5088 | } | |||
5089 | ||||
5090 | void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF, | |||
5091 | const Expr *ReductionOp, | |||
5092 | const Expr *PrivateRef, | |||
5093 | const DeclRefExpr *LHS, | |||
5094 | const DeclRefExpr *RHS) { | |||
5095 | if (PrivateRef->getType()->isArrayType()) { | |||
5096 | // Emit reduction for array section. | |||
5097 | const auto *LHSVar = cast<VarDecl>(LHS->getDecl()); | |||
5098 | const auto *RHSVar = cast<VarDecl>(RHS->getDecl()); | |||
5099 | EmitOMPAggregateReduction( | |||
5100 | CGF, PrivateRef->getType(), LHSVar, RHSVar, | |||
5101 | [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) { | |||
5102 | emitReductionCombiner(CGF, ReductionOp); | |||
5103 | }); | |||
5104 | } else { | |||
5105 | // Emit reduction for array subscript or single variable. | |||
5106 | emitReductionCombiner(CGF, ReductionOp); | |||
5107 | } | |||
5108 | } | |||
5109 | ||||
5110 | void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc, | |||
5111 | ArrayRef<const Expr *> Privates, | |||
5112 | ArrayRef<const Expr *> LHSExprs, | |||
5113 | ArrayRef<const Expr *> RHSExprs, | |||
5114 | ArrayRef<const Expr *> ReductionOps, | |||
5115 | ReductionOptionsTy Options) { | |||
5116 | if (!CGF.HaveInsertPoint()) | |||
5117 | return; | |||
5118 | ||||
5119 | bool WithNowait = Options.WithNowait; | |||
5120 | bool SimpleReduction = Options.SimpleReduction; | |||
5121 | ||||
5122 | // Next code should be emitted for reduction: | |||
5123 | // | |||
5124 | // static kmp_critical_name lock = { 0 }; | |||
5125 | // | |||
5126 | // void reduce_func(void *lhs[<n>], void *rhs[<n>]) { | |||
5127 | // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]); | |||
5128 | // ... | |||
5129 | // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1], | |||
5130 | // *(Type<n>-1*)rhs[<n>-1]); | |||
5131 | // } | |||
5132 | // | |||
5133 | // ... | |||
5134 | // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; | |||
5135 | // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), | |||
5136 | // RedList, reduce_func, &<lock>)) { | |||
5137 | // case 1: | |||
5138 | // ... | |||
5139 | // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); | |||
5140 | // ... | |||
5141 | // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); | |||
5142 | // break; | |||
5143 | // case 2: | |||
5144 | // ... | |||
5145 | // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); | |||
5146 | // ... | |||
5147 | // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);] | |||
5148 | // break; | |||
5149 | // default:; | |||
5150 | // } | |||
5151 | // | |||
5152 | // if SimpleReduction is true, only the next code is generated: | |||
5153 | // ... | |||
5154 | // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); | |||
5155 | // ... | |||
5156 | ||||
5157 | ASTContext &C = CGM.getContext(); | |||
5158 | ||||
5159 | if (SimpleReduction) { | |||
5160 | CodeGenFunction::RunCleanupsScope Scope(CGF); | |||
5161 | const auto *IPriv = Privates.begin(); | |||
5162 | const auto *ILHS = LHSExprs.begin(); | |||
5163 | const auto *IRHS = RHSExprs.begin(); | |||
5164 | for (const Expr *E : ReductionOps) { | |||
5165 | emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), | |||
5166 | cast<DeclRefExpr>(*IRHS)); | |||
5167 | ++IPriv; | |||
5168 | ++ILHS; | |||
5169 | ++IRHS; | |||
5170 | } | |||
5171 | return; | |||
5172 | } | |||
5173 | ||||
5174 | // 1. Build a list of reduction variables. | |||
5175 | // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]}; | |||
5176 | auto Size = RHSExprs.size(); | |||
5177 | for (const Expr *E : Privates) { | |||
5178 | if (E->getType()->isVariablyModifiedType()) | |||
5179 | // Reserve place for array size. | |||
5180 | ++Size; | |||
5181 | } | |||
5182 | llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size); | |||
5183 | QualType ReductionArrayTy = | |||
5184 | C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal, | |||
5185 | /*IndexTypeQuals=*/0); | |||
5186 | Address ReductionList = | |||
5187 | CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list"); | |||
5188 | const auto *IPriv = Privates.begin(); | |||
5189 | unsigned Idx = 0; | |||
5190 | for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) { | |||
5191 | Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx); | |||
5192 | CGF.Builder.CreateStore( | |||
5193 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5194 | CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy), | |||
5195 | Elem); | |||
5196 | if ((*IPriv)->getType()->isVariablyModifiedType()) { | |||
5197 | // Store array size. | |||
5198 | ++Idx; | |||
5199 | Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx); | |||
5200 | llvm::Value *Size = CGF.Builder.CreateIntCast( | |||
5201 | CGF.getVLASize( | |||
5202 | CGF.getContext().getAsVariableArrayType((*IPriv)->getType())) | |||
5203 | .NumElts, | |||
5204 | CGF.SizeTy, /*isSigned=*/false); | |||
5205 | CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy), | |||
5206 | Elem); | |||
5207 | } | |||
5208 | } | |||
5209 | ||||
5210 | // 2. Emit reduce_func(). | |||
5211 | llvm::Function *ReductionFn = | |||
5212 | emitReductionFunction(Loc, CGF.ConvertTypeForMem(ReductionArrayTy), | |||
5213 | Privates, LHSExprs, RHSExprs, ReductionOps); | |||
5214 | ||||
5215 | // 3. Create static kmp_critical_name lock = { 0 }; | |||
5216 | std::string Name = getName({"reduction"}); | |||
5217 | llvm::Value *Lock = getCriticalRegionLock(Name); | |||
5218 | ||||
5219 | // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), | |||
5220 | // RedList, reduce_func, &<lock>); | |||
5221 | llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE); | |||
5222 | llvm::Value *ThreadId = getThreadID(CGF, Loc); | |||
5223 | llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy); | |||
5224 | llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5225 | ReductionList.getPointer(), CGF.VoidPtrTy); | |||
5226 | llvm::Value *Args[] = { | |||
5227 | IdentTLoc, // ident_t *<loc> | |||
5228 | ThreadId, // i32 <gtid> | |||
5229 | CGF.Builder.getInt32(RHSExprs.size()), // i32 <n> | |||
5230 | ReductionArrayTySize, // size_type sizeof(RedList) | |||
5231 | RL, // void *RedList | |||
5232 | ReductionFn, // void (*) (void *, void *) <reduce_func> | |||
5233 | Lock // kmp_critical_name *&<lock> | |||
5234 | }; | |||
5235 | llvm::Value *Res = CGF.EmitRuntimeCall( | |||
5236 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5237 | CGM.getModule(), | |||
5238 | WithNowait ? OMPRTL___kmpc_reduce_nowait : OMPRTL___kmpc_reduce), | |||
5239 | Args); | |||
5240 | ||||
5241 | // 5. Build switch(res) | |||
5242 | llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default"); | |||
5243 | llvm::SwitchInst *SwInst = | |||
5244 | CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2); | |||
5245 | ||||
5246 | // 6. Build case 1: | |||
5247 | // ... | |||
5248 | // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); | |||
5249 | // ... | |||
5250 | // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); | |||
5251 | // break; | |||
5252 | llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1"); | |||
5253 | SwInst->addCase(CGF.Builder.getInt32(1), Case1BB); | |||
5254 | CGF.EmitBlock(Case1BB); | |||
5255 | ||||
5256 | // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); | |||
5257 | llvm::Value *EndArgs[] = { | |||
5258 | IdentTLoc, // ident_t *<loc> | |||
5259 | ThreadId, // i32 <gtid> | |||
5260 | Lock // kmp_critical_name *&<lock> | |||
5261 | }; | |||
5262 | auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps]( | |||
5263 | CodeGenFunction &CGF, PrePostActionTy &Action) { | |||
5264 | CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); | |||
5265 | const auto *IPriv = Privates.begin(); | |||
5266 | const auto *ILHS = LHSExprs.begin(); | |||
5267 | const auto *IRHS = RHSExprs.begin(); | |||
5268 | for (const Expr *E : ReductionOps) { | |||
5269 | RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), | |||
5270 | cast<DeclRefExpr>(*IRHS)); | |||
5271 | ++IPriv; | |||
5272 | ++ILHS; | |||
5273 | ++IRHS; | |||
5274 | } | |||
5275 | }; | |||
5276 | RegionCodeGenTy RCG(CodeGen); | |||
5277 | CommonActionTy Action( | |||
5278 | nullptr, std::nullopt, | |||
5279 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5280 | CGM.getModule(), WithNowait ? OMPRTL___kmpc_end_reduce_nowait | |||
5281 | : OMPRTL___kmpc_end_reduce), | |||
5282 | EndArgs); | |||
5283 | RCG.setAction(Action); | |||
5284 | RCG(CGF); | |||
5285 | ||||
5286 | CGF.EmitBranch(DefaultBB); | |||
5287 | ||||
5288 | // 7. Build case 2: | |||
5289 | // ... | |||
5290 | // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); | |||
5291 | // ... | |||
5292 | // break; | |||
5293 | llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2"); | |||
5294 | SwInst->addCase(CGF.Builder.getInt32(2), Case2BB); | |||
5295 | CGF.EmitBlock(Case2BB); | |||
5296 | ||||
5297 | auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps]( | |||
5298 | CodeGenFunction &CGF, PrePostActionTy &Action) { | |||
5299 | const auto *ILHS = LHSExprs.begin(); | |||
5300 | const auto *IRHS = RHSExprs.begin(); | |||
5301 | const auto *IPriv = Privates.begin(); | |||
5302 | for (const Expr *E : ReductionOps) { | |||
5303 | const Expr *XExpr = nullptr; | |||
5304 | const Expr *EExpr = nullptr; | |||
5305 | const Expr *UpExpr = nullptr; | |||
5306 | BinaryOperatorKind BO = BO_Comma; | |||
5307 | if (const auto *BO = dyn_cast<BinaryOperator>(E)) { | |||
5308 | if (BO->getOpcode() == BO_Assign) { | |||
5309 | XExpr = BO->getLHS(); | |||
5310 | UpExpr = BO->getRHS(); | |||
5311 | } | |||
5312 | } | |||
5313 | // Try to emit update expression as a simple atomic. | |||
5314 | const Expr *RHSExpr = UpExpr; | |||
5315 | if (RHSExpr) { | |||
5316 | // Analyze RHS part of the whole expression. | |||
5317 | if (const auto *ACO = dyn_cast<AbstractConditionalOperator>( | |||
5318 | RHSExpr->IgnoreParenImpCasts())) { | |||
5319 | // If this is a conditional operator, analyze its condition for | |||
5320 | // min/max reduction operator. | |||
5321 | RHSExpr = ACO->getCond(); | |||
5322 | } | |||
5323 | if (const auto *BORHS = | |||
5324 | dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) { | |||
5325 | EExpr = BORHS->getRHS(); | |||
5326 | BO = BORHS->getOpcode(); | |||
5327 | } | |||
5328 | } | |||
5329 | if (XExpr) { | |||
5330 | const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); | |||
5331 | auto &&AtomicRedGen = [BO, VD, | |||
5332 | Loc](CodeGenFunction &CGF, const Expr *XExpr, | |||
5333 | const Expr *EExpr, const Expr *UpExpr) { | |||
5334 | LValue X = CGF.EmitLValue(XExpr); | |||
5335 | RValue E; | |||
5336 | if (EExpr) | |||
5337 | E = CGF.EmitAnyExpr(EExpr); | |||
5338 | CGF.EmitOMPAtomicSimpleUpdateExpr( | |||
5339 | X, E, BO, /*IsXLHSInRHSPart=*/true, | |||
5340 | llvm::AtomicOrdering::Monotonic, Loc, | |||
5341 | [&CGF, UpExpr, VD, Loc](RValue XRValue) { | |||
5342 | CodeGenFunction::OMPPrivateScope PrivateScope(CGF); | |||
5343 | Address LHSTemp = CGF.CreateMemTemp(VD->getType()); | |||
5344 | CGF.emitOMPSimpleStore( | |||
5345 | CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue, | |||
5346 | VD->getType().getNonReferenceType(), Loc); | |||
5347 | PrivateScope.addPrivate(VD, LHSTemp); | |||
5348 | (void)PrivateScope.Privatize(); | |||
5349 | return CGF.EmitAnyExpr(UpExpr); | |||
5350 | }); | |||
5351 | }; | |||
5352 | if ((*IPriv)->getType()->isArrayType()) { | |||
5353 | // Emit atomic reduction for array section. | |||
5354 | const auto *RHSVar = | |||
5355 | cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); | |||
5356 | EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar, | |||
5357 | AtomicRedGen, XExpr, EExpr, UpExpr); | |||
5358 | } else { | |||
5359 | // Emit atomic reduction for array subscript or single variable. | |||
5360 | AtomicRedGen(CGF, XExpr, EExpr, UpExpr); | |||
5361 | } | |||
5362 | } else { | |||
5363 | // Emit as a critical region. | |||
5364 | auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *, | |||
5365 | const Expr *, const Expr *) { | |||
5366 | CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); | |||
5367 | std::string Name = RT.getName({"atomic_reduction"}); | |||
5368 | RT.emitCriticalRegion( | |||
5369 | CGF, Name, | |||
5370 | [=](CodeGenFunction &CGF, PrePostActionTy &Action) { | |||
5371 | Action.Enter(CGF); | |||
5372 | emitReductionCombiner(CGF, E); | |||
5373 | }, | |||
5374 | Loc); | |||
5375 | }; | |||
5376 | if ((*IPriv)->getType()->isArrayType()) { | |||
5377 | const auto *LHSVar = | |||
5378 | cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); | |||
5379 | const auto *RHSVar = | |||
5380 | cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); | |||
5381 | EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar, | |||
5382 | CritRedGen); | |||
5383 | } else { | |||
5384 | CritRedGen(CGF, nullptr, nullptr, nullptr); | |||
5385 | } | |||
5386 | } | |||
5387 | ++ILHS; | |||
5388 | ++IRHS; | |||
5389 | ++IPriv; | |||
5390 | } | |||
5391 | }; | |||
5392 | RegionCodeGenTy AtomicRCG(AtomicCodeGen); | |||
5393 | if (!WithNowait) { | |||
5394 | // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>); | |||
5395 | llvm::Value *EndArgs[] = { | |||
5396 | IdentTLoc, // ident_t *<loc> | |||
5397 | ThreadId, // i32 <gtid> | |||
5398 | Lock // kmp_critical_name *&<lock> | |||
5399 | }; | |||
5400 | CommonActionTy Action(nullptr, std::nullopt, | |||
5401 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5402 | CGM.getModule(), OMPRTL___kmpc_end_reduce), | |||
5403 | EndArgs); | |||
5404 | AtomicRCG.setAction(Action); | |||
5405 | AtomicRCG(CGF); | |||
5406 | } else { | |||
5407 | AtomicRCG(CGF); | |||
5408 | } | |||
5409 | ||||
5410 | CGF.EmitBranch(DefaultBB); | |||
5411 | CGF.EmitBlock(DefaultBB, /*IsFinished=*/true); | |||
5412 | } | |||
5413 | ||||
5414 | /// Generates unique name for artificial threadprivate variables. | |||
5415 | /// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>" | |||
5416 | static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix, | |||
5417 | const Expr *Ref) { | |||
5418 | SmallString<256> Buffer; | |||
5419 | llvm::raw_svector_ostream Out(Buffer); | |||
5420 | const clang::DeclRefExpr *DE; | |||
5421 | const VarDecl *D = ::getBaseDecl(Ref, DE); | |||
5422 | if (!D) | |||
5423 | D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl()); | |||
5424 | D = D->getCanonicalDecl(); | |||
5425 | std::string Name = CGM.getOpenMPRuntime().getName( | |||
5426 | {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)}); | |||
5427 | Out << Prefix << Name << "_" | |||
5428 | << D->getCanonicalDecl()->getBeginLoc().getRawEncoding(); | |||
5429 | return std::string(Out.str()); | |||
5430 | } | |||
5431 | ||||
5432 | /// Emits reduction initializer function: | |||
5433 | /// \code | |||
5434 | /// void @.red_init(void* %arg, void* %orig) { | |||
5435 | /// %0 = bitcast void* %arg to <type>* | |||
5436 | /// store <type> <init>, <type>* %0 | |||
5437 | /// ret void | |||
5438 | /// } | |||
5439 | /// \endcode | |||
5440 | static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM, | |||
5441 | SourceLocation Loc, | |||
5442 | ReductionCodeGen &RCG, unsigned N) { | |||
5443 | ASTContext &C = CGM.getContext(); | |||
5444 | QualType VoidPtrTy = C.VoidPtrTy; | |||
5445 | VoidPtrTy.addRestrict(); | |||
5446 | FunctionArgList Args; | |||
5447 | ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, VoidPtrTy, | |||
5448 | ImplicitParamDecl::Other); | |||
5449 | ImplicitParamDecl ParamOrig(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, VoidPtrTy, | |||
5450 | ImplicitParamDecl::Other); | |||
5451 | Args.emplace_back(&Param); | |||
5452 | Args.emplace_back(&ParamOrig); | |||
5453 | const auto &FnInfo = | |||
5454 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
5455 | llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); | |||
5456 | std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""}); | |||
5457 | auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, | |||
5458 | Name, &CGM.getModule()); | |||
5459 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); | |||
5460 | Fn->setDoesNotRecurse(); | |||
5461 | CodeGenFunction CGF(CGM); | |||
5462 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); | |||
5463 | QualType PrivateType = RCG.getPrivateType(N); | |||
5464 | Address PrivateAddr = CGF.EmitLoadOfPointer( | |||
5465 | CGF.Builder.CreateElementBitCast( | |||
5466 | CGF.GetAddrOfLocalVar(&Param), | |||
5467 | CGF.ConvertTypeForMem(PrivateType)->getPointerTo()), | |||
5468 | C.getPointerType(PrivateType)->castAs<PointerType>()); | |||
5469 | llvm::Value *Size = nullptr; | |||
5470 | // If the size of the reduction item is non-constant, load it from global | |||
5471 | // threadprivate variable. | |||
5472 | if (RCG.getSizes(N).second) { | |||
5473 | Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( | |||
5474 | CGF, CGM.getContext().getSizeType(), | |||
5475 | generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); | |||
5476 | Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, | |||
5477 | CGM.getContext().getSizeType(), Loc); | |||
5478 | } | |||
5479 | RCG.emitAggregateType(CGF, N, Size); | |||
5480 | Address OrigAddr = Address::invalid(); | |||
5481 | // If initializer uses initializer from declare reduction construct, emit a | |||
5482 | // pointer to the address of the original reduction item (reuired by reduction | |||
5483 | // initializer) | |||
5484 | if (RCG.usesReductionInitializer(N)) { | |||
5485 | Address SharedAddr = CGF.GetAddrOfLocalVar(&ParamOrig); | |||
5486 | OrigAddr = CGF.EmitLoadOfPointer( | |||
5487 | SharedAddr, | |||
5488 | CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr()); | |||
5489 | } | |||
5490 | // Emit the initializer: | |||
5491 | // %0 = bitcast void* %arg to <type>* | |||
5492 | // store <type> <init>, <type>* %0 | |||
5493 | RCG.emitInitialization(CGF, N, PrivateAddr, OrigAddr, | |||
5494 | [](CodeGenFunction &) { return false; }); | |||
5495 | CGF.FinishFunction(); | |||
5496 | return Fn; | |||
5497 | } | |||
5498 | ||||
5499 | /// Emits reduction combiner function: | |||
5500 | /// \code | |||
5501 | /// void @.red_comb(void* %arg0, void* %arg1) { | |||
5502 | /// %lhs = bitcast void* %arg0 to <type>* | |||
5503 | /// %rhs = bitcast void* %arg1 to <type>* | |||
5504 | /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs) | |||
5505 | /// store <type> %2, <type>* %lhs | |||
5506 | /// ret void | |||
5507 | /// } | |||
5508 | /// \endcode | |||
5509 | static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM, | |||
5510 | SourceLocation Loc, | |||
5511 | ReductionCodeGen &RCG, unsigned N, | |||
5512 | const Expr *ReductionOp, | |||
5513 | const Expr *LHS, const Expr *RHS, | |||
5514 | const Expr *PrivateRef) { | |||
5515 | ASTContext &C = CGM.getContext(); | |||
5516 | const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl()); | |||
5517 | const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl()); | |||
5518 | FunctionArgList Args; | |||
5519 | ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, | |||
5520 | C.VoidPtrTy, ImplicitParamDecl::Other); | |||
5521 | ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
5522 | ImplicitParamDecl::Other); | |||
5523 | Args.emplace_back(&ParamInOut); | |||
5524 | Args.emplace_back(&ParamIn); | |||
5525 | const auto &FnInfo = | |||
5526 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
5527 | llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); | |||
5528 | std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""}); | |||
5529 | auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, | |||
5530 | Name, &CGM.getModule()); | |||
5531 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); | |||
5532 | Fn->setDoesNotRecurse(); | |||
5533 | CodeGenFunction CGF(CGM); | |||
5534 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); | |||
5535 | llvm::Value *Size = nullptr; | |||
5536 | // If the size of the reduction item is non-constant, load it from global | |||
5537 | // threadprivate variable. | |||
5538 | if (RCG.getSizes(N).second) { | |||
5539 | Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( | |||
5540 | CGF, CGM.getContext().getSizeType(), | |||
5541 | generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); | |||
5542 | Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, | |||
5543 | CGM.getContext().getSizeType(), Loc); | |||
5544 | } | |||
5545 | RCG.emitAggregateType(CGF, N, Size); | |||
5546 | // Remap lhs and rhs variables to the addresses of the function arguments. | |||
5547 | // %lhs = bitcast void* %arg0 to <type>* | |||
5548 | // %rhs = bitcast void* %arg1 to <type>* | |||
5549 | CodeGenFunction::OMPPrivateScope PrivateScope(CGF); | |||
5550 | PrivateScope.addPrivate( | |||
5551 | LHSVD, | |||
5552 | // Pull out the pointer to the variable. | |||
5553 | CGF.EmitLoadOfPointer( | |||
5554 | CGF.Builder.CreateElementBitCast( | |||
5555 | CGF.GetAddrOfLocalVar(&ParamInOut), | |||
5556 | CGF.ConvertTypeForMem(LHSVD->getType())->getPointerTo()), | |||
5557 | C.getPointerType(LHSVD->getType())->castAs<PointerType>())); | |||
5558 | PrivateScope.addPrivate( | |||
5559 | RHSVD, | |||
5560 | // Pull out the pointer to the variable. | |||
5561 | CGF.EmitLoadOfPointer( | |||
5562 | CGF.Builder.CreateElementBitCast( | |||
5563 | CGF.GetAddrOfLocalVar(&ParamIn), | |||
5564 | CGF.ConvertTypeForMem(RHSVD->getType())->getPointerTo()), | |||
5565 | C.getPointerType(RHSVD->getType())->castAs<PointerType>())); | |||
5566 | PrivateScope.Privatize(); | |||
5567 | // Emit the combiner body: | |||
5568 | // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs) | |||
5569 | // store <type> %2, <type>* %lhs | |||
5570 | CGM.getOpenMPRuntime().emitSingleReductionCombiner( | |||
5571 | CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS), | |||
5572 | cast<DeclRefExpr>(RHS)); | |||
5573 | CGF.FinishFunction(); | |||
5574 | return Fn; | |||
5575 | } | |||
5576 | ||||
5577 | /// Emits reduction finalizer function: | |||
5578 | /// \code | |||
5579 | /// void @.red_fini(void* %arg) { | |||
5580 | /// %0 = bitcast void* %arg to <type>* | |||
5581 | /// <destroy>(<type>* %0) | |||
5582 | /// ret void | |||
5583 | /// } | |||
5584 | /// \endcode | |||
5585 | static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM, | |||
5586 | SourceLocation Loc, | |||
5587 | ReductionCodeGen &RCG, unsigned N) { | |||
5588 | if (!RCG.needCleanups(N)) | |||
5589 | return nullptr; | |||
5590 | ASTContext &C = CGM.getContext(); | |||
5591 | FunctionArgList Args; | |||
5592 | ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, | |||
5593 | ImplicitParamDecl::Other); | |||
5594 | Args.emplace_back(&Param); | |||
5595 | const auto &FnInfo = | |||
5596 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); | |||
5597 | llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); | |||
5598 | std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""}); | |||
5599 | auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, | |||
5600 | Name, &CGM.getModule()); | |||
5601 | CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); | |||
5602 | Fn->setDoesNotRecurse(); | |||
5603 | CodeGenFunction CGF(CGM); | |||
5604 | CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); | |||
5605 | Address PrivateAddr = CGF.EmitLoadOfPointer( | |||
5606 | CGF.GetAddrOfLocalVar(&Param), C.VoidPtrTy.castAs<PointerType>()); | |||
5607 | llvm::Value *Size = nullptr; | |||
5608 | // If the size of the reduction item is non-constant, load it from global | |||
5609 | // threadprivate variable. | |||
5610 | if (RCG.getSizes(N).second) { | |||
5611 | Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( | |||
5612 | CGF, CGM.getContext().getSizeType(), | |||
5613 | generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); | |||
5614 | Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, | |||
5615 | CGM.getContext().getSizeType(), Loc); | |||
5616 | } | |||
5617 | RCG.emitAggregateType(CGF, N, Size); | |||
5618 | // Emit the finalizer body: | |||
5619 | // <destroy>(<type>* %0) | |||
5620 | RCG.emitCleanups(CGF, N, PrivateAddr); | |||
5621 | CGF.FinishFunction(Loc); | |||
5622 | return Fn; | |||
5623 | } | |||
5624 | ||||
5625 | llvm::Value *CGOpenMPRuntime::emitTaskReductionInit( | |||
5626 | CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, | |||
5627 | ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) { | |||
5628 | if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty()) | |||
5629 | return nullptr; | |||
5630 | ||||
5631 | // Build typedef struct: | |||
5632 | // kmp_taskred_input { | |||
5633 | // void *reduce_shar; // shared reduction item | |||
5634 | // void *reduce_orig; // original reduction item used for initialization | |||
5635 | // size_t reduce_size; // size of data item | |||
5636 | // void *reduce_init; // data initialization routine | |||
5637 | // void *reduce_fini; // data finalization routine | |||
5638 | // void *reduce_comb; // data combiner routine | |||
5639 | // kmp_task_red_flags_t flags; // flags for additional info from compiler | |||
5640 | // } kmp_taskred_input_t; | |||
5641 | ASTContext &C = CGM.getContext(); | |||
5642 | RecordDecl *RD = C.buildImplicitRecord("kmp_taskred_input_t"); | |||
5643 | RD->startDefinition(); | |||
5644 | const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5645 | const FieldDecl *OrigFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5646 | const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType()); | |||
5647 | const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5648 | const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5649 | const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); | |||
5650 | const FieldDecl *FlagsFD = addFieldToRecordDecl( | |||
5651 | C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false)); | |||
5652 | RD->completeDefinition(); | |||
5653 | QualType RDType = C.getRecordType(RD); | |||
5654 | unsigned Size = Data.ReductionVars.size(); | |||
5655 | llvm::APInt ArraySize(/*numBits=*/64, Size); | |||
5656 | QualType ArrayRDType = C.getConstantArrayType( | |||
5657 | RDType, ArraySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0); | |||
5658 | // kmp_task_red_input_t .rd_input.[Size]; | |||
5659 | Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input."); | |||
5660 | ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionOrigs, | |||
5661 | Data.ReductionCopies, Data.ReductionOps); | |||
5662 | for (unsigned Cnt = 0; Cnt < Size; ++Cnt) { | |||
5663 | // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt]; | |||
5664 | llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0), | |||
5665 | llvm::ConstantInt::get(CGM.SizeTy, Cnt)}; | |||
5666 | llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP( | |||
5667 | TaskRedInput.getElementType(), TaskRedInput.getPointer(), Idxs, | |||
5668 | /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc, | |||
5669 | ".rd_input.gep."); | |||
5670 | LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType); | |||
5671 | // ElemLVal.reduce_shar = &Shareds[Cnt]; | |||
5672 | LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD); | |||
5673 | RCG.emitSharedOrigLValue(CGF, Cnt); | |||
5674 | llvm::Value *CastedShared = | |||
5675 | CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer(CGF)); | |||
5676 | CGF.EmitStoreOfScalar(CastedShared, SharedLVal); | |||
5677 | // ElemLVal.reduce_orig = &Origs[Cnt]; | |||
5678 | LValue OrigLVal = CGF.EmitLValueForField(ElemLVal, OrigFD); | |||
5679 | llvm::Value *CastedOrig = | |||
5680 | CGF.EmitCastToVoidPtr(RCG.getOrigLValue(Cnt).getPointer(CGF)); | |||
5681 | CGF.EmitStoreOfScalar(CastedOrig, OrigLVal); | |||
5682 | RCG.emitAggregateType(CGF, Cnt); | |||
5683 | llvm::Value *SizeValInChars; | |||
5684 | llvm::Value *SizeVal; | |||
5685 | std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt); | |||
5686 | // We use delayed creation/initialization for VLAs and array sections. It is | |||
5687 | // required because runtime does not provide the way to pass the sizes of | |||
5688 | // VLAs/array sections to initializer/combiner/finalizer functions. Instead | |||
5689 | // threadprivate global variables are used to store these values and use | |||
5690 | // them in the functions. | |||
5691 | bool DelayedCreation = !!SizeVal; | |||
5692 | SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy, | |||
5693 | /*isSigned=*/false); | |||
5694 | LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD); | |||
5695 | CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal); | |||
5696 | // ElemLVal.reduce_init = init; | |||
5697 | LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD); | |||
5698 | llvm::Value *InitAddr = | |||
5699 | CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt)); | |||
5700 | CGF.EmitStoreOfScalar(InitAddr, InitLVal); | |||
5701 | // ElemLVal.reduce_fini = fini; | |||
5702 | LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD); | |||
5703 | llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt); | |||
5704 | llvm::Value *FiniAddr = Fini | |||
5705 | ? CGF.EmitCastToVoidPtr(Fini) | |||
5706 | : llvm::ConstantPointerNull::get(CGM.VoidPtrTy); | |||
5707 | CGF.EmitStoreOfScalar(FiniAddr, FiniLVal); | |||
5708 | // ElemLVal.reduce_comb = comb; | |||
5709 | LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD); | |||
5710 | llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction( | |||
5711 | CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt], | |||
5712 | RHSExprs[Cnt], Data.ReductionCopies[Cnt])); | |||
5713 | CGF.EmitStoreOfScalar(CombAddr, CombLVal); | |||
5714 | // ElemLVal.flags = 0; | |||
5715 | LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD); | |||
5716 | if (DelayedCreation) { | |||
5717 | CGF.EmitStoreOfScalar( | |||
5718 | llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*isSigned=*/true), | |||
5719 | FlagsLVal); | |||
5720 | } else | |||
5721 | CGF.EmitNullInitialization(FlagsLVal.getAddress(CGF), | |||
5722 | FlagsLVal.getType()); | |||
5723 | } | |||
5724 | if (Data.IsReductionWithTaskMod) { | |||
5725 | // Build call void *__kmpc_taskred_modifier_init(ident_t *loc, int gtid, int | |||
5726 | // is_ws, int num, void *data); | |||
5727 | llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc); | |||
5728 | llvm::Value *GTid = CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), | |||
5729 | CGM.IntTy, /*isSigned=*/true); | |||
5730 | llvm::Value *Args[] = { | |||
5731 | IdentTLoc, GTid, | |||
5732 | llvm::ConstantInt::get(CGM.IntTy, Data.IsWorksharingReduction ? 1 : 0, | |||
5733 | /*isSigned=*/true), | |||
5734 | llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true), | |||
5735 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( | |||
5736 | TaskRedInput.getPointer(), CGM.VoidPtrTy)}; | |||
5737 | return CGF.EmitRuntimeCall( | |||
5738 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5739 | CGM.getModule(), OMPRTL___kmpc_taskred_modifier_init), | |||
5740 | Args); | |||
5741 | } | |||
5742 | // Build call void *__kmpc_taskred_init(int gtid, int num_data, void *data); | |||
5743 | llvm::Value *Args[] = { | |||
5744 | CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy, | |||
5745 | /*isSigned=*/true), | |||
5746 | llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true), | |||
5747 | CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(), | |||
5748 | CGM.VoidPtrTy)}; | |||
5749 | return CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( | |||
5750 | CGM.getModule(), OMPRTL___kmpc_taskred_init), | |||
5751 | Args); | |||
5752 | } | |||
5753 | ||||
5754 | void CGOpenMPRuntime::emitTaskReductionFini(CodeGenFunction &CGF, | |||
5755 | SourceLocation Loc, | |||
5756 | bool IsWorksharingReduction) { | |||
5757 | // Build call void *__kmpc_taskred_modifier_init(ident_t *loc, int gtid, int | |||
5758 | // is_ws, int num, void *data); | |||
5759 | llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc); | |||
5760 | llvm::Value *GTid = CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), | |||
5761 | CGM.IntTy, /*isSigned=*/true); | |||
5762 | llvm::Value *Args[] = {IdentTLoc, GTid, | |||
5763 | llvm::ConstantInt::get(CGM.IntTy, | |||
5764 | IsWorksharingReduction ? 1 : 0, | |||
5765 | /*isSigned=*/true)}; | |||
5766 | (void)CGF.EmitRuntimeCall( | |||
5767 | OMPBuilder.getOrCreateRuntimeFunction( | |||
5768 | CGM.getModule(), OMPRTL___kmpc_task_reduction_modifier_fini), | |||
5769 | Args); | |||
5770 | } | |||
5771 | ||||
5772 | void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF, | |||
5773 | SourceLocation Loc, | |||
5774 | ReductionCodeGen &RCG, | |||
5775 | unsigned N) { | |||
5776 | auto Sizes = RCG.getSizes(N); | |||
5777 | // Emit threadprivate global variable if the type is non-constant | |||
5778 | // (Sizes.second = nullptr). | |||
5779 | if (Sizes.second) { | |||
5780 | llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy, | |||
5781 | /*isSigned=*/false); | |||
5782 | Address SizeAddr = getAddrOfArtificialThreadPrivate( | |||
5783 | CGF, CGM.getContext().getSizeType(), | |||
5784 | generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); | |||
5785 | CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false); | |||
5786 | } | |||
5787 | } | |||
5788 | ||||
5789 |