Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TClingCallFunc.cxx
Go to the documentation of this file.
1// root/core/meta
2// vim: sw=3
3// Author: Paul Russo 30/07/2012
4// Author: Vassil Vassilev 9/02/2013
5
6/*************************************************************************
7 * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. *
8 * All rights reserved. *
9 * *
10 * For the licensing terms see $ROOTSYS/LICENSE. *
11 * For the list of contributors see $ROOTSYS/README/CREDITS. *
12 *************************************************************************/
13
14/** \class TClingCallFunc
15Emulation of the CINT CallFunc class.
16
17The CINT C++ interpreter provides an interface for calling
18functions through the generated wrappers in dictionaries with
19the CallFunc class. This class provides the same functionality,
20using an interface as close as possible to CallFunc but the
21function metadata and calling service comes from the Cling
22C++ interpreter and the Clang C++ compiler, not CINT.
23*/
24
25#include "TClingCallFunc.h"
26
27#include "TClingClassInfo.h"
28#include "TClingMethodInfo.h"
29#include "TInterpreterValue.h"
30#include "TClingUtils.h"
31
32#include "TError.h"
33#include "TCling.h"
34
35#include "cling/Interpreter/CompilationOptions.h"
36#include "cling/Interpreter/Interpreter.h"
37#include "cling/Interpreter/LookupHelper.h"
38#include "cling/Interpreter/Transaction.h"
39#include "cling/Interpreter/Value.h"
40#include "cling/Utils/AST.h"
41
42#include "clang/AST/ASTContext.h"
43#include "clang/AST/Decl.h"
44#include "clang/AST/DeclCXX.h"
45#include "clang/AST/GlobalDecl.h"
46#include "clang/AST/PrettyPrinter.h"
47#include "clang/AST/RecordLayout.h"
48#include "clang/AST/Type.h"
49#include "clang/Frontend/CompilerInstance.h"
50#include "clang/Lex/Preprocessor.h"
51#include "clang/Sema/Sema.h"
52#include "clang/Sema/Lookup.h"
53
54#include "llvm/ADT/APInt.h"
55#include "llvm/ExecutionEngine/ExecutionEngine.h"
56#include "llvm/ExecutionEngine/GenericValue.h"
57#include "llvm/Support/Casting.h"
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/DerivedTypes.h"
61#include "llvm/IR/Function.h"
62#include "llvm/IR/GlobalValue.h"
63#include "llvm/IR/Module.h"
64#include "llvm/IR/Type.h"
65
66#include "clang/Sema/SemaInternal.h"
67
68#include <map>
69#include <string>
70#include <sstream>
71
72using namespace ROOT;
73using namespace llvm;
74using namespace clang;
75using namespace std;
76
77static unsigned long long gWrapperSerial = 0LL;
78static const string kIndentString(" ");
79
80static map<const Decl *, void *> gWrapperStore;
81static map<const Decl *, void *> gCtorWrapperStore;
82static map<const Decl *, void *> gDtorWrapperStore;
83
84static
85inline
86void
87indent(ostringstream &buf, int indent_level)
88{
89 for (int i = 0; i < indent_level; ++i) {
90 buf << kIndentString;
91 }
92}
93
94static
95void
96EvaluateExpr(cling::Interpreter &interp, const Expr *E, cling::Value &V)
97{
98 // Evaluate an Expr* and return its cling::Value
99 ASTContext &C = interp.getCI()->getASTContext();
100 clang::Expr::EvalResult evalRes;
101 if (E->EvaluateAsInt(evalRes, C, /*AllowSideEffects*/Expr::SE_NoSideEffects)) {
102 APSInt res = evalRes.Val.getInt();
103 // IntTy or maybe better E->getType()?
104 V = cling::Value(C.IntTy, interp);
105 // We must use the correct signedness otherwise the zero extension
106 // fails if the actual type is strictly less than long long.
107 if (res.isSigned())
108 V.getLL() = res.getSExtValue();
109 else
110 V.getULL() = res.getZExtValue();
111 return;
112 }
113 // TODO: Build a wrapper around the expression to avoid decompilation and
114 // compilation and other string operations.
115 PrintingPolicy Policy(C.getPrintingPolicy());
116 Policy.SuppressTagKeyword = true;
117 Policy.SuppressUnwrittenScope = false;
118 Policy.SuppressInitializers = false;
119 Policy.AnonymousTagLocations = false;
120 string buf;
121 raw_string_ostream out(buf);
122 E->printPretty(out, /*Helper=*/0, Policy, /*Indentation=*/0);
123 out << ';'; // no value printing
124 out.flush();
125 // Evaluate() will set V to invalid if evaluation fails.
126 interp.evaluate(buf, V);
127}
128
129namespace {
130 template <typename returnType>
131 returnType sv_to(const cling::Value &val)
132 {
133 QualType QT = val.getType().getCanonicalType();
134 if (const BuiltinType *BT =
135 dyn_cast<BuiltinType>(&*QT)) {
136 //
137 // WARNING!!!
138 //
139 // This switch is organized in order-of-declaration
140 // so that the produced assembly code is optimal.
141 // Do not reorder!
142 //
143 switch (BT->getKind()) {
144 case BuiltinType::Void:
145 // CINT used to expect a result of 0.
146 return (returnType) 0;
147 break;
148 //
149 // Unsigned Types
150 //
151 case BuiltinType::Bool:
152 case BuiltinType::Char_U: // char on targets where it is unsigned
153 case BuiltinType::UChar:
154 return (returnType) val.getULL();
155 break;
156
157 case BuiltinType::WChar_U:
158 // wchar_t on targets where it is unsigned
159 // The standard doesn't allow to specify signednedd of wchar_t
160 // thus this maps simply to wchar_t.
161 return (returnType)(wchar_t) val.getULL();
162 break;
163
164 case BuiltinType::Char16:
165 case BuiltinType::Char32:
166 case BuiltinType::UShort:
167 case BuiltinType::UInt:
168 case BuiltinType::ULong:
169 case BuiltinType::ULongLong:
170 return (returnType) val.getULL();
171 break;
172
173 case BuiltinType::UInt128:
174 // __uint128_t
175 break;
176
177 //
178 // Signed Types
179 //
180 case BuiltinType::Char_S: // char on targets where it is signed
181 case BuiltinType::SChar:
182 return (returnType) val.getLL();
183 break;
184
185 case BuiltinType::WChar_S:
186 // wchar_t on targets where it is signed
187 // The standard doesn't allow to specify signednedd of wchar_t
188 // thus this maps simply to wchar_t.
189 return (returnType)(wchar_t) val.getLL();
190 break;
191
192 case BuiltinType::Short:
193 case BuiltinType::Int:
194 case BuiltinType::Long:
195 case BuiltinType::LongLong:
196 return (returnType) val.getLL();
197 break;
198
199 case BuiltinType::Int128:
200 break;
201
202 case BuiltinType::Half:
203 // half in OpenCL, __fp16 in ARM NEON
204 break;
205
206 case BuiltinType::Float:
207 return (returnType) val.getFloat();
208 break;
209 case BuiltinType::Double:
210 return (returnType) val.getDouble();
211 break;
212 case BuiltinType::LongDouble:
213 return (returnType) val.getLongDouble();
214 break;
215
216 case BuiltinType::NullPtr:
217 return (returnType) 0;
218 break;
219
220 default:
221 break;
222 }
223 }
224 if (QT->isPointerType() || QT->isArrayType() || QT->isRecordType() ||
225 QT->isReferenceType()) {
226 return (returnType)(Longptr_t) val.getPtr();
227 }
228 if (const EnumType *ET = dyn_cast<EnumType>(&*QT)) {
229 if (ET->getDecl()->getIntegerType()->hasSignedIntegerRepresentation())
230 return (returnType) val.getLL();
231 else
232 return (returnType) val.getULL();
233 }
234 if (QT->isMemberPointerType()) {
235 const MemberPointerType *MPT = QT->getAs<MemberPointerType>();
236 if (MPT && MPT->isMemberDataPointer()) {
237 return (returnType)(ptrdiff_t)val.getPtr();
238 }
239 return (returnType)(Longptr_t) val.getPtr();
240 }
241 ::Error("TClingCallFunc::sv_to", "Invalid Type!");
242 QT->dump();
243 return 0;
244 }
245
246 static
247 long long sv_to_long_long(const cling::Value &val)
248 {
249 return sv_to<long long>(val);
250 }
251 static
252 unsigned long long sv_to_ulong_long(const cling::Value &val)
253 {
254 return sv_to<unsigned long long>(val);
255 }
256
257} // unnamed namespace.
258
260{
261 // This function is non-const to use caching overload of GetDecl()!
262 return GetDecl()->getMinRequiredArguments();
263}
264
265void *TClingCallFunc::compile_wrapper(const string &wrapper_name, const string &wrapper,
266 bool withAccessControl/*=true*/)
267{
268 return fInterp->compileFunction(wrapper_name, wrapper, false /*ifUnique*/,
269 withAccessControl);
270}
271
272void TClingCallFunc::collect_type_info(QualType &QT, ostringstream &typedefbuf, std::ostringstream &callbuf,
273 string &type_name, EReferenceType &refType, bool &isPointer, int indent_level,
274 bool forArgument)
275{
276 //
277 // Collect information about type type of a function parameter
278 // needed for building the wrapper function.
279 //
280 const FunctionDecl *FD = GetDecl();
281 PrintingPolicy Policy(FD->getASTContext().getPrintingPolicy());
282 refType = kNotReference;
283 if (QT->isRecordType() && forArgument) {
285 return;
286 }
287 if (QT->isFunctionPointerType()) {
288 string fp_typedef_name;
289 {
290 ostringstream nm;
291 nm << "FP" << gWrapperSerial++;
292 type_name = nm.str();
293 raw_string_ostream OS(fp_typedef_name);
294 QT.print(OS, Policy, type_name);
295 OS.flush();
296 }
297 for (int i = 0; i < indent_level; ++i) {
298 typedefbuf << kIndentString;
299 }
300 typedefbuf << "typedef " << fp_typedef_name << ";\n";
301 return;
302 } else if (QT->isMemberPointerType()) {
303 string mp_typedef_name;
304 {
305 ostringstream nm;
306 nm << "MP" << gWrapperSerial++;
307 type_name = nm.str();
308 raw_string_ostream OS(mp_typedef_name);
309 QT.print(OS, Policy, type_name);
310 OS.flush();
311 }
312 for (int i = 0; i < indent_level; ++i) {
313 typedefbuf << kIndentString;
314 }
315 typedefbuf << "typedef " << mp_typedef_name << ";\n";
316 return;
317 } else if (QT->isPointerType()) {
318 isPointer = true;
319 QT = cast<clang::PointerType>(QT)->getPointeeType();
320 } else if (QT->isReferenceType()) {
321 if (QT->isRValueReferenceType()) refType = kRValueReference;
322 else refType = kLValueReference;
323 QT = cast<ReferenceType>(QT)->getPointeeType();
324 }
325 // Fall through for the array type to deal with reference/pointer ro array type.
326 if (QT->isArrayType()) {
327 string ar_typedef_name;
328 {
329 ostringstream ar;
330 ar << "AR" << gWrapperSerial++;
331 type_name = ar.str();
332 raw_string_ostream OS(ar_typedef_name);
333 QT.print(OS, Policy, type_name);
334 OS.flush();
335 }
336 for (int i = 0; i < indent_level; ++i) {
337 typedefbuf << kIndentString;
338 }
339 typedefbuf << "typedef " << ar_typedef_name << ";\n";
340 return;
341 }
343}
344
345void TClingCallFunc::make_narg_ctor(const unsigned N, ostringstream &typedefbuf,
346 ostringstream &callbuf, const string &class_name,
347 int indent_level)
348{
349 // Make a code string that follows this pattern:
350 //
351 // new ClassName(args...)
352 //
353 const FunctionDecl *FD = GetDecl();
354
355 callbuf << "new " << class_name << "(";
356 for (unsigned i = 0U; i < N; ++i) {
357 const ParmVarDecl *PVD = FD->getParamDecl(i);
358 QualType Ty = PVD->getType();
359 QualType QT = Ty.getCanonicalType();
360 string type_name;
362 bool isPointer = false;
363 collect_type_info(QT, typedefbuf, callbuf, type_name,
364 refType, isPointer, indent_level, true);
365 if (i) {
366 callbuf << ',';
367 if (i % 2) {
368 callbuf << ' ';
369 } else {
370 callbuf << "\n";
371 for (int j = 0; j <= indent_level; ++j) {
372 callbuf << kIndentString;
373 }
374 }
375 }
376 if (refType != kNotReference) {
377 callbuf << "(" << type_name.c_str() <<
378 (refType == kLValueReference ? "&" : "&&") << ")*(" << type_name.c_str() << "*)args["
379 << i << "]";
380 } else if (isPointer) {
381 callbuf << "*(" << type_name.c_str() << "**)args["
382 << i << "]";
383 } else {
384 callbuf << "*(" << type_name.c_str() << "*)args[" << i << "]";
385 }
386 }
387 callbuf << ")";
388}
389
390void TClingCallFunc::make_narg_call(const std::string &return_type, const unsigned N, ostringstream &typedefbuf,
391 ostringstream &callbuf, const string &class_name, int indent_level)
392{
393 //
394 // Make a code string that follows this pattern:
395 //
396 // ((<class>*)obj)-><method>(*(<arg-i-type>*)args[i], ...)
397 //
398 const FunctionDecl *FD = GetDecl();
399
400 // Sometimes it's necessary that we cast the function we want to call first
401 // to its explicit function type before calling it. This is supposed to prevent
402 // that we accidentially ending up in a function that is not the one we're
403 // supposed to call here (e.g. because the C++ function lookup decides to take
404 // another function that better fits).
405 // This method has some problems, e.g. when we call a function with default
406 // arguments and we don't provide all arguments, we would fail with this pattern.
407 // Same applies with member methods which seem to cause parse failures even when
408 // we supply the object parameter.
409 // Therefore we only use it in cases where we know it works and set this variable
410 // to true when we do.
411 bool ShouldCastFunction = !isa<CXXMethodDecl>(FD) && N == FD->getNumParams();
412 if (ShouldCastFunction) {
413 callbuf << "(";
414 callbuf << "(";
415 callbuf << return_type << " (&)";
416 {
417 callbuf << "(";
418 for (unsigned i = 0U; i < N; ++i) {
419 if (i) {
420 callbuf << ',';
421 if (i % 2) {
422 callbuf << ' ';
423 } else {
424 callbuf << "\n";
425 for (int j = 0; j <= indent_level; ++j) {
426 callbuf << kIndentString;
427 }
428 }
429 }
430 const ParmVarDecl *PVD = FD->getParamDecl(i);
431 QualType Ty = PVD->getType();
432 QualType QT = Ty.getCanonicalType();
433 std::string arg_type;
435 callbuf << arg_type;
436 }
437 if (FD->isVariadic())
438 callbuf << ", ...";
439 callbuf << ")";
440 }
441
442 callbuf << ")";
443 }
444
445 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
446 // This is a class, struct, or union member.
447 if (MD->isConst())
448 callbuf << "((const " << class_name << "*)obj)->";
449 else
450 callbuf << "((" << class_name << "*)obj)->";
451 } else if (const NamedDecl *ND =
452 dyn_cast<NamedDecl>(GetDeclContext())) {
453 // This is a namespace member.
454 (void) ND;
455 callbuf << class_name << "::";
456 }
457 // callbuf << fMethod->Name() << "(";
458 {
459 std::string name;
460 {
461 llvm::raw_string_ostream stream(name);
462 FD->getNameForDiagnostic(stream, FD->getASTContext().getPrintingPolicy(), /*Qualified=*/false);
463 }
464 callbuf << name;
465 }
466 if (ShouldCastFunction) callbuf << ")";
467
468 callbuf << "(";
469 for (unsigned i = 0U; i < N; ++i) {
470 const ParmVarDecl *PVD = FD->getParamDecl(i);
471 QualType Ty = PVD->getType();
472 QualType QT = Ty.getCanonicalType();
473 string type_name;
475 bool isPointer = false;
476 collect_type_info(QT, typedefbuf, callbuf, type_name, refType, isPointer, indent_level, true);
477
478 if (i) {
479 callbuf << ',';
480 if (i % 2) {
481 callbuf << ' ';
482 } else {
483 callbuf << "\n";
484 for (int j = 0; j <= indent_level; ++j) {
485 callbuf << kIndentString;
486 }
487 }
488 }
489
490 if (refType != kNotReference) {
491 callbuf << "(" << type_name.c_str() <<
492 (refType == kLValueReference ? "&" : "&&") << ")*(" << type_name.c_str() << "*)args["
493 << i << "]";
494 } else if (isPointer) {
495 callbuf << "*(" << type_name.c_str() << "**)args["
496 << i << "]";
497 } else {
498 // pointer falls back to non-pointer case; the argument preserves
499 // the "pointerness" (i.e. doesn't reference the value).
500 callbuf << "*(" << type_name.c_str() << "*)args[" << i << "]";
501 }
502 }
503 callbuf << ")";
504}
505
506void TClingCallFunc::make_narg_ctor_with_return(const unsigned N, const string &class_name,
507 ostringstream &buf, int indent_level)
508{
509 // Make a code string that follows this pattern:
510 //
511 // if (ret) {
512 // (*(ClassName**)ret) = new ClassName(args...);
513 // }
514 // else {
515 // new ClassName(args...);
516 // }
517 //
518 for (int i = 0; i < indent_level; ++i) {
519 buf << kIndentString;
520 }
521 buf << "if (ret) {\n";
522 ++indent_level;
523 {
524 ostringstream typedefbuf;
525 ostringstream callbuf;
526 //
527 // Write the return value assignment part.
528 //
529 for (int i = 0; i < indent_level; ++i) {
530 callbuf << kIndentString;
531 }
532 callbuf << "(*(" << class_name << "**)ret) = ";
533 //
534 // Write the actual new expression.
535 //
536 make_narg_ctor(N, typedefbuf, callbuf, class_name, indent_level);
537 //
538 // End the new expression statement.
539 //
540 callbuf << ";\n";
541 for (int i = 0; i < indent_level; ++i) {
542 callbuf << kIndentString;
543 }
544 callbuf << "return;\n";
545 //
546 // Output the whole new expression and return statement.
547 //
548 buf << typedefbuf.str() << callbuf.str();
549 }
550 --indent_level;
551 for (int i = 0; i < indent_level; ++i) {
552 buf << kIndentString;
553 }
554 buf << "}\n";
555 for (int i = 0; i < indent_level; ++i) {
556 buf << kIndentString;
557 }
558 buf << "else {\n";
559 ++indent_level;
560 {
561 ostringstream typedefbuf;
562 ostringstream callbuf;
563 for (int i = 0; i < indent_level; ++i) {
564 callbuf << kIndentString;
565 }
566 make_narg_ctor(N, typedefbuf, callbuf, class_name, indent_level);
567 callbuf << ";\n";
568 for (int i = 0; i < indent_level; ++i) {
569 callbuf << kIndentString;
570 }
571 callbuf << "return;\n";
572 buf << typedefbuf.str() << callbuf.str();
573 }
574 --indent_level;
575 for (int i = 0; i < indent_level; ++i) {
576 buf << kIndentString;
577 }
578 buf << "}\n";
579}
580
581///////////////////////////////////////////////////////////////////////////////
582// Returns the DeclContext corresponding to fMethod's Decl.
583// \Note that this might be a FunctionDecl or a UsingShadowDecl; we use the
584// DeclContext of the UsingShadowDecl e.g. for constructing a derived class
585// object, even if invoking a function made available by a using declaration
586// of a constructor of a base class (ROOT-11010).
587
588const clang::DeclContext *TClingCallFunc::GetDeclContext() const {
589 return fMethod->GetDecl()->getDeclContext();
590}
591
592int TClingCallFunc::get_wrapper_code(std::string &wrapper_name, std::string &wrapper)
593{
594 const FunctionDecl *FD = GetDecl();
595 assert(FD && "generate_wrapper called without a function decl!");
596 ASTContext &Context = FD->getASTContext();
597 PrintingPolicy Policy(Context.getPrintingPolicy());
598 //
599 // Get the class or namespace name.
600 //
601 string class_name;
602 const clang::DeclContext *DC = GetDeclContext();
603 if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC)) {
604 // This is a class, struct, or union member.
605 QualType QT(TD->getTypeForDecl(), 0);
607 } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
608 // This is a namespace member.
609 raw_string_ostream stream(class_name);
610 ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
611 stream.flush();
612 }
613 //
614 // Check to make sure that we can
615 // instantiate and codegen this function.
616 //
617 bool needInstantiation = false;
618 const FunctionDecl *Definition = 0;
619 if (!FD->isDefined(Definition)) {
620 FunctionDecl::TemplatedKind TK = FD->getTemplatedKind();
621 switch (TK) {
622 case FunctionDecl::TK_NonTemplate: {
623 // Ordinary function, not a template specialization.
624 // Note: This might be ok, the body might be defined
625 // in a library, and all we have seen is the
626 // header file.
627 //::Error("TClingCallFunc::make_wrapper",
628 // "Cannot make wrapper for a function which is "
629 // "declared but not defined!");
630 // return 0;
631 } break;
632 case FunctionDecl::TK_FunctionTemplate: {
633 // This decl is actually a function template,
634 // not a function at all.
635 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template!");
636 return 0;
637 } break;
638 case FunctionDecl::TK_MemberSpecialization: {
639 // This function is the result of instantiating an ordinary
640 // member function of a class template, or of instantiating
641 // an ordinary member function of a class member of a class
642 // template, or of specializing a member function template
643 // of a class template, or of specializing a member function
644 // template of a class member of a class template.
645 if (!FD->isTemplateInstantiation()) {
646 // We are either TSK_Undeclared or
647 // TSK_ExplicitSpecialization.
648 // Note: This might be ok, the body might be defined
649 // in a library, and all we have seen is the
650 // header file.
651 //::Error("TClingCallFunc::make_wrapper",
652 // "Cannot make wrapper for a function template "
653 // "explicit specialization which is declared "
654 // "but not defined!");
655 // return 0;
656 break;
657 }
658 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
659 if (!Pattern) {
660 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a member function "
661 "instantiation with no pattern!");
662 return 0;
663 }
664 FunctionDecl::TemplatedKind PTK = Pattern->getTemplatedKind();
665 TemplateSpecializationKind PTSK = Pattern->getTemplateSpecializationKind();
666 if (
667 // The pattern is an ordinary member function.
668 (PTK == FunctionDecl::TK_NonTemplate) ||
669 // The pattern is an explicit specialization, and
670 // so is not a template.
671 ((PTK != FunctionDecl::TK_FunctionTemplate) &&
672 ((PTSK == TSK_Undeclared) || (PTSK == TSK_ExplicitSpecialization)))) {
673 // Note: This might be ok, the body might be defined
674 // in a library, and all we have seen is the
675 // header file.
676 break;
677 } else if (!Pattern->hasBody()) {
678 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a member function "
679 "instantiation with no body!");
680 return 0;
681 }
682 if (FD->isImplicitlyInstantiable()) {
683 needInstantiation = true;
684 }
685 } break;
686 case FunctionDecl::TK_FunctionTemplateSpecialization: {
687 // This function is the result of instantiating a function
688 // template or possibly an explicit specialization of a
689 // function template. Could be a namespace scope function or a
690 // member function.
691 if (!FD->isTemplateInstantiation()) {
692 // We are either TSK_Undeclared or
693 // TSK_ExplicitSpecialization.
694 // Note: This might be ok, the body might be defined
695 // in a library, and all we have seen is the
696 // header file.
697 //::Error("TClingCallFunc::make_wrapper",
698 // "Cannot make wrapper for a function template "
699 // "explicit specialization which is declared "
700 // "but not defined!");
701 // return 0;
702 break;
703 }
704 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
705 if (!Pattern) {
706 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template"
707 "instantiation with no pattern!");
708 return 0;
709 }
710 FunctionDecl::TemplatedKind PTK = Pattern->getTemplatedKind();
711 TemplateSpecializationKind PTSK = Pattern->getTemplateSpecializationKind();
712 if (
713 // The pattern is an ordinary member function.
714 (PTK == FunctionDecl::TK_NonTemplate) ||
715 // The pattern is an explicit specialization, and
716 // so is not a template.
717 ((PTK != FunctionDecl::TK_FunctionTemplate) &&
718 ((PTSK == TSK_Undeclared) || (PTSK == TSK_ExplicitSpecialization)))) {
719 // Note: This might be ok, the body might be defined
720 // in a library, and all we have seen is the
721 // header file.
722 break;
723 }
724 if (!Pattern->hasBody()) {
725 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template"
726 "instantiation with no body!");
727 return 0;
728 }
729 if (FD->isImplicitlyInstantiable()) {
730 needInstantiation = true;
731 }
732 } break;
733 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
734 // This function is the result of instantiating or
735 // specializing a member function of a class template,
736 // or a member function of a class member of a class template,
737 // or a member function template of a class template, or a
738 // member function template of a class member of a class
739 // template where at least some part of the function is
740 // dependent on a template argument.
741 if (!FD->isTemplateInstantiation()) {
742 // We are either TSK_Undeclared or
743 // TSK_ExplicitSpecialization.
744 // Note: This might be ok, the body might be defined
745 // in a library, and all we have seen is the
746 // header file.
747 //::Error("TClingCallFunc::make_wrapper",
748 // "Cannot make wrapper for a dependent function "
749 // "template explicit specialization which is declared "
750 // "but not defined!");
751 // return 0;
752 break;
753 }
754 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
755 if (!Pattern) {
756 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a dependent function template"
757 "instantiation with no pattern!");
758 return 0;
759 }
760 FunctionDecl::TemplatedKind PTK = Pattern->getTemplatedKind();
761 TemplateSpecializationKind PTSK = Pattern->getTemplateSpecializationKind();
762 if (
763 // The pattern is an ordinary member function.
764 (PTK == FunctionDecl::TK_NonTemplate) ||
765 // The pattern is an explicit specialization, and
766 // so is not a template.
767 ((PTK != FunctionDecl::TK_FunctionTemplate) &&
768 ((PTSK == TSK_Undeclared) || (PTSK == TSK_ExplicitSpecialization)))) {
769 // Note: This might be ok, the body might be defined
770 // in a library, and all we have seen is the
771 // header file.
772 break;
773 }
774 if (!Pattern->hasBody()) {
775 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a dependent function template"
776 "instantiation with no body!");
777 return 0;
778 }
779 if (FD->isImplicitlyInstantiable()) {
780 needInstantiation = true;
781 }
782 } break;
783 default: {
784 // Will only happen if clang implementation changes.
785 // Protect ourselves in case that happens.
786 ::Error("TClingCallFunc::make_wrapper", "Unhandled template kind!");
787 return 0;
788 } break;
789 }
790 // We do not set needInstantiation to true in these cases:
791 //
792 // isInvalidDecl()
793 // TSK_Undeclared
794 // TSK_ExplicitInstantiationDefinition
795 // TSK_ExplicitSpecialization && !getClassScopeSpecializationPattern()
796 // TSK_ExplicitInstantiationDeclaration &&
797 // getTemplateInstantiationPattern() &&
798 // PatternDecl->hasBody() &&
799 // !PatternDecl->isInlined()
800 //
801 // Set it true in these cases:
802 //
803 // TSK_ImplicitInstantiation
804 // TSK_ExplicitInstantiationDeclaration && (!getPatternDecl() ||
805 // !PatternDecl->hasBody() || PatternDecl->isInlined())
806 //
807 }
808 if (needInstantiation) {
809 clang::FunctionDecl *FDmod = const_cast<clang::FunctionDecl *>(FD);
810 clang::Sema &S = fInterp->getSema();
811 // Could trigger deserialization of decls.
812 cling::Interpreter::PushTransactionRAII RAII(fInterp);
813 S.InstantiateFunctionDefinition(SourceLocation(), FDmod,
814 /*Recursive=*/true,
815 /*DefinitionRequired=*/true);
816 if (!FD->isDefined(Definition)) {
817 ::Error("TClingCallFunc::make_wrapper", "Failed to force template instantiation!");
818 return 0;
819 }
820 }
821 if (Definition) {
822 FunctionDecl::TemplatedKind TK = Definition->getTemplatedKind();
823 switch (TK) {
824 case FunctionDecl::TK_NonTemplate: {
825 // Ordinary function, not a template specialization.
826 if (Definition->isDeleted()) {
827 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted function!");
828 return 0;
829 } else if (Definition->isLateTemplateParsed()) {
830 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
831 "function!");
832 return 0;
833 }
834 // else if (Definition->isDefaulted()) {
835 // // Might not have a body, but we can still use it.
836 //}
837 // else {
838 // // Has a body.
839 //}
840 } break;
841 case FunctionDecl::TK_FunctionTemplate: {
842 // This decl is actually a function template,
843 // not a function at all.
844 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template!");
845 return 0;
846 } break;
847 case FunctionDecl::TK_MemberSpecialization: {
848 // This function is the result of instantiating an ordinary
849 // member function of a class template or of a member class
850 // of a class template.
851 if (Definition->isDeleted()) {
852 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted member function "
853 "of a specialization!");
854 return 0;
855 } else if (Definition->isLateTemplateParsed()) {
856 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
857 "member function of a specialization!");
858 return 0;
859 }
860 // else if (Definition->isDefaulted()) {
861 // // Might not have a body, but we can still use it.
862 //}
863 // else {
864 // // Has a body.
865 //}
866 } break;
867 case FunctionDecl::TK_FunctionTemplateSpecialization: {
868 // This function is the result of instantiating a function
869 // template or possibly an explicit specialization of a
870 // function template. Could be a namespace scope function or a
871 // member function.
872 if (Definition->isDeleted()) {
873 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted function "
874 "template specialization!");
875 return 0;
876 } else if (Definition->isLateTemplateParsed()) {
877 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
878 "function template specialization!");
879 return 0;
880 }
881 // else if (Definition->isDefaulted()) {
882 // // Might not have a body, but we can still use it.
883 //}
884 // else {
885 // // Has a body.
886 //}
887 } break;
888 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
889 // This function is the result of instantiating or
890 // specializing a member function of a class template,
891 // or a member function of a class member of a class template,
892 // or a member function template of a class template, or a
893 // member function template of a class member of a class
894 // template where at least some part of the function is
895 // dependent on a template argument.
896 if (Definition->isDeleted()) {
897 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted dependent function "
898 "template specialization!");
899 return 0;
900 } else if (Definition->isLateTemplateParsed()) {
901 ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
902 "dependent function template specialization!");
903 return 0;
904 }
905 // else if (Definition->isDefaulted()) {
906 // // Might not have a body, but we can still use it.
907 //}
908 // else {
909 // // Has a body.
910 //}
911 } break;
912 default: {
913 // Will only happen if clang implementation changes.
914 // Protect ourselves in case that happens.
915 ::Error("TClingCallFunc::make_wrapper", "Unhandled template kind!");
916 return 0;
917 } break;
918 }
919 }
920 unsigned min_args = GetMinRequiredArguments();
921 unsigned num_params = FD->getNumParams();
922 //
923 // Make the wrapper name.
924 //
925 {
926 ostringstream buf;
927 buf << "__cf";
928 // const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
929 // string mn;
930 // fInterp->maybeMangleDeclName(ND, mn);
931 // buf << '_' << mn;
932 buf << '_' << gWrapperSerial++;
933 wrapper_name = buf.str();
934 }
935 //
936 // Write the wrapper code.
937 // FIXME: this should be synthesized into the AST!
938 //
939 int indent_level = 0;
940 ostringstream buf;
941 buf << "#pragma clang diagnostic push\n"
942 "#pragma clang diagnostic ignored \"-Wformat-security\"\n"
943 "__attribute__((used)) "
944 "__attribute__((annotate(\"__cling__ptrcheck(off)\")))\n"
945 "extern \"C\" void ";
946 buf << wrapper_name;
947 buf << "(void* obj, int nargs, void** args, void* ret)\n"
948 "{\n";
949 ++indent_level;
950 if (min_args == num_params) {
951 // No parameters with defaults.
952 make_narg_call_with_return(num_params, class_name, buf, indent_level);
953 } else {
954 // We need one function call clause compiled for every
955 // possible number of arguments per call.
956 for (unsigned N = min_args; N <= num_params; ++N) {
957 for (int i = 0; i < indent_level; ++i) {
958 buf << kIndentString;
959 }
960 buf << "if (nargs == " << N << ") {\n";
961 ++indent_level;
962 make_narg_call_with_return(N, class_name, buf, indent_level);
963 --indent_level;
964 for (int i = 0; i < indent_level; ++i) {
965 buf << kIndentString;
966 }
967 buf << "}\n";
968 }
969 }
970 --indent_level;
971 buf << "}\n"
972 "#pragma clang diagnostic pop";
973 wrapper = buf.str();
974 return 1;
975}
976
977void TClingCallFunc::make_narg_call_with_return(const unsigned N, const string &class_name,
978 ostringstream &buf, int indent_level)
979{
980 // Make a code string that follows this pattern:
981 //
982 // if (ret) {
983 // new (ret) (return_type) ((class_name*)obj)->func(args...);
984 // }
985 // else {
986 // (void)(((class_name*)obj)->func(args...));
987 // }
988 //
989 const FunctionDecl *FD = GetDecl();
990 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
991 if (N <= 1 && llvm::isa<UsingShadowDecl>(GetFunctionOrShadowDecl())) {
992 auto SpecMemKind = fInterp->getSema().getSpecialMember(CD);
993 if ((N == 0 && SpecMemKind == clang::Sema::CXXDefaultConstructor) ||
994 (N == 1 &&
995 (SpecMemKind == clang::Sema::CXXCopyConstructor || SpecMemKind == clang::Sema::CXXMoveConstructor))) {
996 // Using declarations cannot inject special members; do not call them
997 // as such. This might happen by using `Base(Base&, int = 12)`, which
998 // is fine to be called as `Derived d(someBase, 42)` but not as
999 // copy constructor of `Derived`.
1000 return;
1001 }
1002 }
1003 make_narg_ctor_with_return(N, class_name, buf, indent_level);
1004 return;
1005 }
1006 QualType QT = FD->getReturnType().getCanonicalType();
1007 if (QT->isVoidType()) {
1008 ostringstream typedefbuf;
1009 ostringstream callbuf;
1010 for (int i = 0; i < indent_level; ++i) {
1011 callbuf << kIndentString;
1012 }
1013 make_narg_call("void", N, typedefbuf, callbuf, class_name, indent_level);
1014 callbuf << ";\n";
1015 for (int i = 0; i < indent_level; ++i) {
1016 callbuf << kIndentString;
1017 }
1018 callbuf << "return;\n";
1019 buf << typedefbuf.str() << callbuf.str();
1020 } else {
1021 for (int i = 0; i < indent_level; ++i) {
1022 buf << kIndentString;
1023 }
1024
1025 string type_name;
1026 EReferenceType refType = kNotReference;
1027 bool isPointer = false;
1028
1029 buf << "if (ret) {\n";
1030 ++indent_level;
1031 {
1032 ostringstream typedefbuf;
1033 ostringstream callbuf;
1034 //
1035 // Write the placement part of the placement new.
1036 //
1037 for (int i = 0; i < indent_level; ++i) {
1038 callbuf << kIndentString;
1039 }
1040 callbuf << "new (ret) ";
1041 collect_type_info(QT, typedefbuf, callbuf, type_name,
1042 refType, isPointer, indent_level, false);
1043 //
1044 // Write the type part of the placement new.
1045 //
1046 callbuf << "(" << type_name.c_str();
1047 if (refType != kNotReference) {
1048 callbuf << "*) (&";
1049 type_name += "&";
1050 } else if (isPointer) {
1051 callbuf << "*) (";
1052 type_name += "*";
1053 } else {
1054 callbuf << ") (";
1055 }
1056 //
1057 // Write the actual function call.
1058 //
1059 make_narg_call(type_name, N, typedefbuf, callbuf, class_name, indent_level);
1060 //
1061 // End the placement new.
1062 //
1063 callbuf << ");\n";
1064 for (int i = 0; i < indent_level; ++i) {
1065 callbuf << kIndentString;
1066 }
1067 callbuf << "return;\n";
1068 //
1069 // Output the whole placement new expression and return statement.
1070 //
1071 buf << typedefbuf.str() << callbuf.str();
1072 }
1073 --indent_level;
1074 for (int i = 0; i < indent_level; ++i) {
1075 buf << kIndentString;
1076 }
1077 buf << "}\n";
1078 for (int i = 0; i < indent_level; ++i) {
1079 buf << kIndentString;
1080 }
1081 buf << "else {\n";
1082 ++indent_level;
1083 {
1084 ostringstream typedefbuf;
1085 ostringstream callbuf;
1086 for (int i = 0; i < indent_level; ++i) {
1087 callbuf << kIndentString;
1088 }
1089 callbuf << "(void)(";
1090 make_narg_call(type_name, N, typedefbuf, callbuf, class_name, indent_level);
1091 callbuf << ");\n";
1092 for (int i = 0; i < indent_level; ++i) {
1093 callbuf << kIndentString;
1094 }
1095 callbuf << "return;\n";
1096 buf << typedefbuf.str() << callbuf.str();
1097 }
1098 --indent_level;
1099 for (int i = 0; i < indent_level; ++i) {
1100 buf << kIndentString;
1101 }
1102 buf << "}\n";
1103 }
1104}
1105
1107{
1109
1110 const Decl *D = GetFunctionOrShadowDecl();
1111 string wrapper_name;
1112 string wrapper;
1113
1114 if (get_wrapper_code(wrapper_name, wrapper) == 0) return 0;
1115
1116 //fprintf(stderr, "%s\n", wrapper.c_str());
1117 //
1118 // Compile the wrapper code.
1119 //
1120 void *F = compile_wrapper(wrapper_name, wrapper);
1121 if (F) {
1122 gWrapperStore.insert(make_pair(D, F));
1123 } else {
1124 ::Error("TClingCallFunc::make_wrapper",
1125 "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1126 wrapper.c_str());
1127 }
1129}
1130
1132 ROOT::TMetaUtils::EIOCtorCategory kind, const std::string &type_name)
1133{
1134 // Make a code string that follows this pattern:
1135 //
1136 // void
1137 // unique_wrapper_ddd(void** ret, void* arena, unsigned long nary)
1138 // {
1139 // if (!arena) {
1140 // if (!nary) {
1141 // *ret = new ClassName;
1142 // }
1143 // else {
1144 // *ret = new ClassName[nary];
1145 // }
1146 // }
1147 // else {
1148 // if (!nary) {
1149 // *ret = new (arena) ClassName;
1150 // }
1151 // else {
1152 // *ret = new (arena) ClassName[nary];
1153 // }
1154 // }
1155 // }
1156 //
1157 // When I/O constructor used:
1158 //
1159 // void
1160 // unique_wrapper_ddd(void** ret, void* arena, unsigned long nary)
1161 // {
1162 // if (!arena) {
1163 // if (!nary) {
1164 // *ret = new ClassName((TRootIOCtor*)nullptr);
1165 // }
1166 // else {
1167 // char *buf = malloc(nary * sizeof(ClassName));
1168 // for (int k=0;k<nary;++k)
1169 // new (buf + k * sizeof(ClassName)) ClassName((TRootIOCtor*)nullptr);
1170 // *ret = buf;
1171 // }
1172 // }
1173 // else {
1174 // if (!nary) {
1175 // *ret = new (arena) ClassName((TRootIOCtor*)nullptr);
1176 // }
1177 // else {
1178 // for (int k=0;k<nary;++k)
1179 // new ((char *) arena + k * sizeof(ClassName)) ClassName((TRootIOCtor*)nullptr);
1180 // *ret = arena;
1181 // }
1182 // }
1183 // }
1184 //
1185 //
1186 // Note:
1187 //
1188 // If the class is of POD type, the form:
1189 //
1190 // new ClassName;
1191 //
1192 // does not initialize the object at all, and the form:
1193 //
1194 // new ClassName();
1195 //
1196 // default-initializes the object.
1197 //
1198 // We are using the form without parentheses because that is what
1199 // CINT did.
1200 //
1201 //--
1202 ASTContext &Context = info->GetDecl()->getASTContext();
1203 PrintingPolicy Policy(Context.getPrintingPolicy());
1204 Policy.SuppressTagKeyword = true;
1205 Policy.SuppressUnwrittenScope = true;
1206 //
1207 // Get the class or namespace name.
1208 //
1209 string class_name;
1210 if (const TypeDecl *TD = dyn_cast<TypeDecl>(info->GetDecl())) {
1211 // This is a class, struct, or union member.
1212 QualType QT(TD->getTypeForDecl(), 0);
1214 } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(info->GetDecl())) {
1215 // This is a namespace member.
1216 raw_string_ostream stream(class_name);
1217 ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
1218 stream.flush();
1219 }
1220
1221
1222 //
1223 // Make the wrapper name.
1224 //
1225 string wrapper_name;
1226 {
1227 ostringstream buf;
1228 buf << "__ctor";
1229 //const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
1230 //string mn;
1231 //fInterp->maybeMangleDeclName(ND, mn);
1232 //buf << '_dtor_' << mn;
1233 buf << '_' << gWrapperSerial++;
1234 wrapper_name = buf.str();
1235 }
1236
1237 string constr_arg;
1239 constr_arg = string("((") + type_name + "*)nullptr)";
1241 constr_arg = string("(*((") + type_name + "*)arena))";
1242
1243 //
1244 // Write the wrapper code.
1245 //
1246 int indent_level = 0;
1247 ostringstream buf;
1248 buf << "__attribute__((used)) ";
1249 buf << "extern \"C\" void ";
1250 buf << wrapper_name;
1251 buf << "(void** ret, void* arena, unsigned long nary)\n";
1252 buf << "{\n";
1253
1254 // if (!arena) {
1255 // if (!nary) {
1256 // *ret = new ClassName;
1257 // }
1258 // else {
1259 // *ret = new ClassName[nary];
1260 // }
1261 // }
1262 indent(buf, ++indent_level);
1263 buf << "if (!arena) {\n";
1264 indent(buf, ++indent_level);
1265 buf << "if (!nary) {\n";
1266 indent(buf, ++indent_level);
1267 buf << "*ret = new " << class_name << constr_arg << ";\n";
1268 indent(buf, --indent_level);
1269 buf << "}\n";
1270 indent(buf, indent_level);
1271 buf << "else {\n";
1272 indent(buf, ++indent_level);
1273 if (constr_arg.empty()) {
1274 buf << "*ret = new " << class_name << "[nary];\n";
1275 } else {
1276 buf << "char *buf = (char *) malloc(nary * sizeof(" << class_name << "));\n";
1277 indent(buf, indent_level);
1278 buf << "for (int k=0;k<nary;++k)\n";
1279 indent(buf, ++indent_level);
1280 buf << "new (buf + k * sizeof(" << class_name << ")) " << class_name << constr_arg << ";\n";
1281 indent(buf, --indent_level);
1282 buf << "*ret = buf;\n";
1283 }
1284 indent(buf, --indent_level);
1285 buf << "}\n";
1286 indent(buf, --indent_level);
1287 buf << "}\n";
1288 // else {
1289 // if (!nary) {
1290 // *ret = new (arena) ClassName;
1291 // }
1292 // else {
1293 // *ret = new (arena) ClassName[nary];
1294 // }
1295 // }
1296 indent(buf, indent_level);
1297 buf << "else {\n";
1298 indent(buf, ++indent_level);
1299 buf << "if (!nary) {\n";
1300 indent(buf, ++indent_level);
1301 buf << "*ret = new (arena) " << class_name << constr_arg << ";\n";
1302 indent(buf, --indent_level);
1303 buf << "}\n";
1304 indent(buf, indent_level);
1305 buf << "else {\n";
1306 indent(buf, ++indent_level);
1307 if (constr_arg.empty()) {
1308 buf << "*ret = new (arena) " << class_name << "[nary];\n";
1309 } else {
1310 buf << "for (int k=0;k<nary;++k)\n";
1311 indent(buf, ++indent_level);
1312 buf << "new ((char *) arena + k * sizeof(" << class_name << ")) " << class_name << constr_arg << ";\n";
1313 indent(buf, --indent_level);
1314 buf << "*ret = arena;\n";
1315 }
1316 indent(buf, --indent_level);
1317 buf << "}\n";
1318 indent(buf, --indent_level);
1319 buf << "}\n";
1320 // End wrapper.
1321 --indent_level;
1322 buf << "}\n";
1323 // Done.
1324 string wrapper(buf.str());
1325 //fprintf(stderr, "%s\n", wrapper.c_str());
1326 //
1327 // Compile the wrapper code.
1328 //
1329 void *F = compile_wrapper(wrapper_name, wrapper,
1330 /*withAccessControl=*/false);
1331 if (F) {
1332 gCtorWrapperStore.insert(make_pair(info->GetDecl(), F));
1333 } else {
1334 ::Error("TClingCallFunc::make_ctor_wrapper",
1335 "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1336 wrapper.c_str());
1337 }
1339}
1340
1343{
1344 // Make a code string that follows this pattern:
1345 //
1346 // void
1347 // unique_wrapper_ddd(void* obj, unsigned long nary, int withFree)
1348 // {
1349 // if (withFree) {
1350 // if (!nary) {
1351 // delete (ClassName*) obj;
1352 // }
1353 // else {
1354 // delete[] (ClassName*) obj;
1355 // }
1356 // }
1357 // else {
1358 // typedef ClassName DtorName;
1359 // if (!nary) {
1360 // ((ClassName*)obj)->~DtorName();
1361 // }
1362 // else {
1363 // for (unsigned long i = nary - 1; i > -1; --i) {
1364 // (((ClassName*)obj)+i)->~DtorName();
1365 // }
1366 // }
1367 // }
1368 // }
1369 //
1370 //--
1371 ASTContext &Context = info->GetDecl()->getASTContext();
1372 PrintingPolicy Policy(Context.getPrintingPolicy());
1373 Policy.SuppressTagKeyword = true;
1374 Policy.SuppressUnwrittenScope = true;
1375 //
1376 // Get the class or namespace name.
1377 //
1378 string class_name;
1379 if (const TypeDecl *TD = dyn_cast<TypeDecl>(info->GetDecl())) {
1380 // This is a class, struct, or union member.
1381 QualType QT(TD->getTypeForDecl(), 0);
1383 } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(info->GetDecl())) {
1384 // This is a namespace member.
1385 raw_string_ostream stream(class_name);
1386 ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
1387 stream.flush();
1388 }
1389 //
1390 // Make the wrapper name.
1391 //
1392 string wrapper_name;
1393 {
1394 ostringstream buf;
1395 buf << "__dtor";
1396 //const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
1397 //string mn;
1398 //fInterp->maybeMangleDeclName(ND, mn);
1399 //buf << '_dtor_' << mn;
1400 buf << '_' << gWrapperSerial++;
1401 wrapper_name = buf.str();
1402 }
1403 //
1404 // Write the wrapper code.
1405 //
1406 int indent_level = 0;
1407 ostringstream buf;
1408 buf << "__attribute__((used)) ";
1409 buf << "extern \"C\" void ";
1410 buf << wrapper_name;
1411 buf << "(void* obj, unsigned long nary, int withFree)\n";
1412 buf << "{\n";
1413 // if (withFree) {
1414 // if (!nary) {
1415 // delete (ClassName*) obj;
1416 // }
1417 // else {
1418 // delete[] (ClassName*) obj;
1419 // }
1420 // }
1421 ++indent_level;
1422 indent(buf, indent_level);
1423 buf << "if (withFree) {\n";
1424 ++indent_level;
1425 indent(buf, indent_level);
1426 buf << "if (!nary) {\n";
1427 ++indent_level;
1428 indent(buf, indent_level);
1429 buf << "delete (" << class_name << "*) obj;\n";
1430 --indent_level;
1431 indent(buf, indent_level);
1432 buf << "}\n";
1433 indent(buf, indent_level);
1434 buf << "else {\n";
1435 ++indent_level;
1436 indent(buf, indent_level);
1437 buf << "delete[] (" << class_name << "*) obj;\n";
1438 --indent_level;
1439 indent(buf, indent_level);
1440 buf << "}\n";
1441 --indent_level;
1442 indent(buf, indent_level);
1443 buf << "}\n";
1444 // else {
1445 // typedef ClassName Nm;
1446 // if (!nary) {
1447 // ((Nm*)obj)->~Nm();
1448 // }
1449 // else {
1450 // for (unsigned long i = nary - 1; i > -1; --i) {
1451 // (((Nm*)obj)+i)->~Nm();
1452 // }
1453 // }
1454 // }
1455 indent(buf, indent_level);
1456 buf << "else {\n";
1457 ++indent_level;
1458 indent(buf, indent_level);
1459 buf << "typedef " << class_name << " Nm;\n";
1460 buf << "if (!nary) {\n";
1461 ++indent_level;
1462 indent(buf, indent_level);
1463 buf << "((Nm*)obj)->~Nm();\n";
1464 --indent_level;
1465 indent(buf, indent_level);
1466 buf << "}\n";
1467 indent(buf, indent_level);
1468 buf << "else {\n";
1469 ++indent_level;
1470 indent(buf, indent_level);
1471 buf << "do {\n";
1472 ++indent_level;
1473 indent(buf, indent_level);
1474 buf << "(((Nm*)obj)+(--nary))->~Nm();\n";
1475 --indent_level;
1476 indent(buf, indent_level);
1477 buf << "} while (nary);\n";
1478 --indent_level;
1479 indent(buf, indent_level);
1480 buf << "}\n";
1481 --indent_level;
1482 indent(buf, indent_level);
1483 buf << "}\n";
1484 // End wrapper.
1485 --indent_level;
1486 buf << "}\n";
1487 // Done.
1488 string wrapper(buf.str());
1489 //fprintf(stderr, "%s\n", wrapper.c_str());
1490 //
1491 // Compile the wrapper code.
1492 //
1493 void *F = compile_wrapper(wrapper_name, wrapper,
1494 /*withAccessControl=*/false);
1495 if (F) {
1496 gDtorWrapperStore.insert(make_pair(info->GetDecl(), F));
1497 } else {
1498 ::Error("TClingCallFunc::make_dtor_wrapper",
1499 "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1500 wrapper.c_str());
1501 }
1502
1504}
1505
1507public:
1508 union {
1509 long double ldbl;
1510 double dbl;
1511 float flt;
1512 //__uint128_t ui128;
1513 //__int128_t i128;
1514 unsigned long long ull;
1515 long long ll;
1516 unsigned long ul;
1517 long l;
1518 unsigned int ui;
1519 int i;
1520 unsigned short us;
1521 short s;
1522 //char32_t c32;
1523 //char16_t c16;
1524 //unsigned wchar_t uwc; - non-standard
1525 wchar_t wc;
1526 unsigned char uc;
1527 signed char sc;
1528 char c;
1529 bool b;
1530 void *vp;
1531 } u;
1532};
1533
1534void TClingCallFunc::exec(void *address, void *ret)
1535{
1536 SmallVector<ValHolder, 8> vh_ary;
1537 SmallVector<void *, 8> vp_ary;
1538
1539 unsigned num_args = fArgVals.size();
1540 {
1542
1543 const FunctionDecl *FD = GetDecl();
1544
1545 //
1546 // Convert the arguments from cling::Value to their
1547 // actual type and store them in a holder for passing to the
1548 // wrapper function by pointer to value.
1549 //
1550 unsigned num_params = FD->getNumParams();
1551
1552 if (num_args < GetMinRequiredArguments()) {
1553 ::Error("TClingCallFunc::exec",
1554 "Not enough arguments provided for %s (%d instead of the minimum %d)",
1555 fMethod->Name(),
1556 num_args, (int)GetMinRequiredArguments());
1557 return;
1558 }
1559 if (address == 0 && dyn_cast<CXXMethodDecl>(FD)
1560 && !(dyn_cast<CXXMethodDecl>(FD))->isStatic()
1561 && !dyn_cast<CXXConstructorDecl>(FD)) {
1562 ::Error("TClingCallFunc::exec",
1563 "The method %s is called without an object.",
1564 fMethod->Name());
1565 return;
1566 }
1567 vh_ary.reserve(num_args);
1568 vp_ary.reserve(num_args);
1569 for (unsigned i = 0U; i < num_args; ++i) {
1570 QualType Ty;
1571 if (i < num_params) {
1572 const ParmVarDecl *PVD = FD->getParamDecl(i);
1573 Ty = PVD->getType();
1574 } else {
1575 Ty = fArgVals[i].getType();
1576 }
1577 QualType QT = Ty.getCanonicalType();
1578 if (const BuiltinType *BT =
1579 dyn_cast<BuiltinType>(&*QT)) {
1580 //
1581 // WARNING!!!
1582 //
1583 // This switch is organized in order-of-declaration
1584 // so that the produced assembly code is optimal.
1585 // Do not reorder!
1586 //
1587 switch (BT->getKind()) {
1588 //
1589 // Builtin Types
1590 //
1591 case BuiltinType::Void: {
1592 // void
1593 ::Error("TClingCallFunc::exec(void*)",
1594 "Invalid type 'Void'!");
1595 return;
1596 }
1597 break;
1598 //
1599 // Unsigned Types
1600 //
1601 case BuiltinType::Bool: {
1602 // bool
1603 ValHolder vh;
1604 vh.u.b = (bool) sv_to_ulong_long(fArgVals[i]);
1605 vh_ary.push_back(vh);
1606 vp_ary.push_back(&vh_ary.back());
1607 }
1608 break;
1609 case BuiltinType::Char_U: {
1610 // char on targets where it is unsigned
1611 ValHolder vh;
1612 vh.u.c = (char) sv_to_ulong_long(fArgVals[i]);
1613 vh_ary.push_back(vh);
1614 vp_ary.push_back(&vh_ary.back());
1615 }
1616 break;
1617 case BuiltinType::UChar: {
1618 // unsigned char
1619 ValHolder vh;
1620 vh.u.uc = (unsigned char) sv_to_ulong_long(fArgVals[i]);
1621 vh_ary.push_back(vh);
1622 vp_ary.push_back(&vh_ary.back());
1623 }
1624 break;
1625 case BuiltinType::WChar_U: {
1626 // wchar_t on targets where it is unsigned.
1627 // The standard doesn't allow to specify signednedd of wchar_t
1628 // thus this maps simply to wchar_t.
1629 ValHolder vh;
1630 vh.u.wc = (wchar_t) sv_to_ulong_long(fArgVals[i]);
1631 vh_ary.push_back(vh);
1632 vp_ary.push_back(&vh_ary.back());
1633 }
1634 break;
1635 case BuiltinType::Char16: {
1636 // char16_t
1637 //ValHolder vh;
1638 //vh.u.c16 = (char16_t) sv_to_ulong_long(fArgVals[i]);
1639 //vh_ary.push_back(vh);
1640 //vp_ary.push_back(&vh_ary.back());
1641 }
1642 break;
1643 case BuiltinType::Char32: {
1644 // char32_t
1645 //ValHolder vh;
1646 //vh.u.c32 = (char32_t) sv_to_ulong_long(fArgVals[i]);
1647 //vh_ary.push_back(vh);
1648 //vp_ary.push_back(&vh_ary.back());
1649 }
1650 break;
1651 case BuiltinType::UShort: {
1652 // unsigned short
1653 ValHolder vh;
1654 vh.u.us = (unsigned short) sv_to_ulong_long(fArgVals[i]);
1655 vh_ary.push_back(vh);
1656 vp_ary.push_back(&vh_ary.back());
1657 }
1658 break;
1659 case BuiltinType::UInt: {
1660 // unsigned int
1661 ValHolder vh;
1662 vh.u.ui = (unsigned int) sv_to_ulong_long(fArgVals[i]);
1663 vh_ary.push_back(vh);
1664 vp_ary.push_back(&vh_ary.back());
1665 }
1666 break;
1667 case BuiltinType::ULong: {
1668 // unsigned long
1669 ValHolder vh;
1670 vh.u.ul = (unsigned long) sv_to_ulong_long(fArgVals[i]);
1671 vh_ary.push_back(vh);
1672 vp_ary.push_back(&vh_ary.back());
1673 }
1674 break;
1675 case BuiltinType::ULongLong: {
1676 // unsigned long long
1677 ValHolder vh;
1678 vh.u.ull = (unsigned long long) sv_to_ulong_long(fArgVals[i]);
1679 vh_ary.push_back(vh);
1680 vp_ary.push_back(&vh_ary.back());
1681 }
1682 break;
1683 case BuiltinType::UInt128: {
1684 // __uint128_t
1685 }
1686 break;
1687 //
1688 // Signed Types
1689 //
1690 //
1691 // Signed Types
1692 //
1693 case BuiltinType::Char_S: {
1694 // char on targets where it is signed
1695 ValHolder vh;
1696 vh.u.c = (char) sv_to_long_long(fArgVals[i]);
1697 vh_ary.push_back(vh);
1698 vp_ary.push_back(&vh_ary.back());
1699 }
1700 break;
1701 case BuiltinType::SChar: {
1702 // signed char
1703 ValHolder vh;
1704 vh.u.sc = (signed char) sv_to_long_long(fArgVals[i]);
1705 vh_ary.push_back(vh);
1706 vp_ary.push_back(&vh_ary.back());
1707 }
1708 break;
1709 case BuiltinType::WChar_S: {
1710 // wchar_t on targets where it is signed.
1711 // The standard doesn't allow to specify signednedd of wchar_t
1712 // thus this maps simply to wchar_t.
1713 ValHolder vh;
1714 vh.u.wc = (wchar_t) sv_to_long_long(fArgVals[i]);
1715 vh_ary.push_back(vh);
1716 vp_ary.push_back(&vh_ary.back());
1717 }
1718 break;
1719 case BuiltinType::Short: {
1720 // short
1721 ValHolder vh;
1722 vh.u.s = (short) sv_to_long_long(fArgVals[i]);
1723 vh_ary.push_back(vh);
1724 vp_ary.push_back(&vh_ary.back());
1725 }
1726 break;
1727 case BuiltinType::Int: {
1728 // int
1729 ValHolder vh;
1730 vh.u.i = (int) sv_to_long_long(fArgVals[i]);
1731 vh_ary.push_back(vh);
1732 vp_ary.push_back(&vh_ary.back());
1733 }
1734 break;
1735 case BuiltinType::Long: {
1736 // long
1737 ValHolder vh;
1738 vh.u.l = (long) sv_to_long_long(fArgVals[i]);
1739 vh_ary.push_back(vh);
1740 vp_ary.push_back(&vh_ary.back());
1741 }
1742 break;
1743 case BuiltinType::LongLong: {
1744 // long long
1745 ValHolder vh;
1746 vh.u.ll = (long long) sv_to_long_long(fArgVals[i]);
1747 vh_ary.push_back(vh);
1748 vp_ary.push_back(&vh_ary.back());
1749 }
1750 break;
1751 case BuiltinType::Int128: {
1752 // __int128_t
1753 ::Error("TClingCallFunc::exec(void*)",
1754 "Invalid type 'Int128'!");
1755 return;
1756 }
1757 break;
1758 case BuiltinType::Half: {
1759 // half in OpenCL, __fp16 in ARM NEON
1760 ::Error("TClingCallFunc::exec(void*)",
1761 "Invalid type 'Half'!");
1762 return;
1763 }
1764 break;
1765 case BuiltinType::Float: {
1766 // float
1767 ValHolder vh;
1768 vh.u.flt = sv_to<float>(fArgVals[i]);
1769 vh_ary.push_back(vh);
1770 vp_ary.push_back(&vh_ary.back());
1771 }
1772 break;
1773 case BuiltinType::Double: {
1774 // double
1775 ValHolder vh;
1776 vh.u.dbl = sv_to<double>(fArgVals[i]);
1777 vh_ary.push_back(vh);
1778 vp_ary.push_back(&vh_ary.back());
1779 }
1780 break;
1781 case BuiltinType::LongDouble: {
1782 // long double
1783 ValHolder vh;
1784 vh.u.ldbl = sv_to<long double>(fArgVals[i]);
1785 vh_ary.push_back(vh);
1786 vp_ary.push_back(&vh_ary.back());
1787 }
1788 break;
1789 //
1790 // Language-Specific Types
1791 //
1792 case BuiltinType::NullPtr: {
1793 // C++11 nullptr
1794 ValHolder vh;
1795 vh.u.vp = fArgVals[i].getPtr();
1796 vh_ary.push_back(vh);
1797 vp_ary.push_back(&vh_ary.back());
1798 }
1799 break;
1800 default: {
1801 // There should be no others. This is here in case
1802 // this changes in the future.
1803 ::Error("TClingCallFunc::exec(void*)",
1804 "Unhandled builtin type!");
1805 QT->dump();
1806 return;
1807 }
1808 break;
1809 }
1810 } else if (QT->isReferenceType()) {
1811 // the argument is already a pointer value (point to the same thing
1812 // as the reference.
1813 vp_ary.push_back((void *) sv_to_ulong_long(fArgVals[i]));
1814 } else if (QT->isPointerType() || QT->isArrayType()) {
1815 ValHolder vh;
1816 vh.u.vp = (void *) sv_to_ulong_long(fArgVals[i]);
1817 vh_ary.push_back(vh);
1818 vp_ary.push_back(&vh_ary.back());
1819 } else if (QT->isRecordType()) {
1820 // the argument is already a pointer value (pointing to object passed
1821 // by value).
1822 vp_ary.push_back((void *) sv_to_ulong_long(fArgVals[i]));
1823 } else if (const EnumType *ET =
1824 dyn_cast<EnumType>(&*QT)) {
1825 // Note: We may need to worry about the underlying type
1826 // of the enum here.
1827 (void) ET;
1828 ValHolder vh;
1829 vh.u.i = (int) sv_to_long_long(fArgVals[i]);
1830 vh_ary.push_back(vh);
1831 vp_ary.push_back(&vh_ary.back());
1832 } else if (QT->isMemberPointerType()) {
1833 ValHolder vh;
1834 vh.u.vp = (void *) sv_to_ulong_long(fArgVals[i]);
1835 vh_ary.push_back(vh);
1836 vp_ary.push_back(&vh_ary.back());
1837 } else {
1838 ::Error("TClingCallFunc::exec(void*)",
1839 "Invalid type (unrecognized)!");
1840 QT->dump();
1841 return;
1842 }
1843 }
1844 } // End of scope holding the lock
1845 (*fWrapper)(address, (int)num_args, (void **)vp_ary.data(), ret);
1846}
1847
1848template <typename T>
1849void TClingCallFunc::execWithLL(void *address, cling::Value *val)
1850{
1851 T ret; // leave uninit for valgrind's sake!
1852 exec(address, &ret);
1853 val->getLL() = ret;
1854}
1855
1856template <typename T>
1857void TClingCallFunc::execWithULL(void *address, cling::Value *val)
1858{
1859 T ret; // leave uninit for valgrind's sake!
1860 exec(address, &ret);
1861 val->getULL() = ret;
1862}
1863
1864// Handle integral types.
1865template <class T>
1867{
1868 ret = cling::Value::Create<T>(QT.getAsOpaquePtr(), *fInterp);
1869 static_assert(std::is_integral<T>::value, "Must be called with integral T");
1870 if (std::is_signed<T>::value)
1871 return [this](void* address, cling::Value& ret) { execWithLL<T>(address, &ret); };
1872 else
1873 return [this](void* address, cling::Value& ret) { execWithULL<T>(address, &ret); };
1874}
1875
1876// Handle builtin types.
1878TClingCallFunc::InitRetAndExecBuiltin(QualType QT, const clang::BuiltinType *BT, cling::Value &ret) {
1879 switch (BT->getKind()) {
1880 case BuiltinType::Void: {
1881 ret = cling::Value::Create<void>(QT.getAsOpaquePtr(), *fInterp);
1882 return [this](void* address, cling::Value& ret) { exec(address, 0); };
1883 break;
1884 }
1885
1886 //
1887 // Unsigned Types
1888 //
1889 case BuiltinType::Bool:
1890 return InitRetAndExecIntegral<bool>(QT, ret);
1891 break;
1892 case BuiltinType::Char_U: // char on targets where it is unsigned
1893 case BuiltinType::UChar:
1894 return InitRetAndExecIntegral<char>(QT, ret);
1895 break;
1896 case BuiltinType::WChar_U:
1897 return InitRetAndExecIntegral<wchar_t>(QT, ret);
1898 break;
1899 case BuiltinType::Char16:
1900 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1901 "Invalid type 'char16_t'!");
1902 return {};
1903 break;
1904 case BuiltinType::Char32:
1905 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1906 "Invalid type 'char32_t'!");
1907 return {};
1908 break;
1909 case BuiltinType::UShort:
1910 return InitRetAndExecIntegral<unsigned short>(QT, ret);
1911 break;
1912 case BuiltinType::UInt:
1913 return InitRetAndExecIntegral<unsigned int>(QT, ret);
1914 break;
1915 case BuiltinType::ULong:
1916 return InitRetAndExecIntegral<unsigned long>(QT, ret);
1917 break;
1918 case BuiltinType::ULongLong:
1919 return InitRetAndExecIntegral<unsigned long long>(QT, ret);
1920 break;
1921 case BuiltinType::UInt128: {
1922 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1923 "Invalid type '__uint128_t'!");
1924 return {};
1925 }
1926 break;
1927
1928 //
1929 // Signed Types
1930 //
1931 case BuiltinType::Char_S: // char on targets where it is signed
1932 case BuiltinType::SChar:
1933 return InitRetAndExecIntegral<signed char>(QT, ret);
1934 break;
1935 case BuiltinType::WChar_S:
1936 // wchar_t on targets where it is signed.
1937 // The standard doesn't allow to specify signednedd of wchar_t
1938 // thus this maps simply to wchar_t.
1939 return InitRetAndExecIntegral<wchar_t>(QT, ret);
1940 break;
1941 case BuiltinType::Short:
1942 return InitRetAndExecIntegral<short>(QT, ret);
1943 break;
1944 case BuiltinType::Int:
1945 return InitRetAndExecIntegral<int>(QT, ret);
1946 break;
1947 case BuiltinType::Long:
1948 return InitRetAndExecIntegral<long>(QT, ret);
1949 break;
1950 case BuiltinType::LongLong:
1951 return InitRetAndExecIntegral<long long>(QT, ret);
1952 break;
1953 case BuiltinType::Int128:
1954 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1955 "Invalid type '__int128_t'!");
1956 return {};
1957 break;
1958 case BuiltinType::Half:
1959 // half in OpenCL, __fp16 in ARM NEON
1960 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1961 "Invalid type 'Half'!");
1962 return {};
1963 break;
1964 case BuiltinType::Float: {
1965 ret = cling::Value::Create<float>(QT.getAsOpaquePtr(), *fInterp);
1966 return [this](void* address, cling::Value& ret) { exec(address, &ret.getFloat()); };
1967 break;
1968 }
1969 case BuiltinType::Double: {
1970 ret = cling::Value::Create<double>(QT.getAsOpaquePtr(), *fInterp);
1971 return [this](void* address, cling::Value& ret) { exec(address, &ret.getDouble()); };
1972 break;
1973 }
1974 case BuiltinType::LongDouble: {
1975 ret = cling::Value::Create<long double>(QT.getAsOpaquePtr(), *fInterp);
1976 return [this](void* address, cling::Value& ret) { exec(address, &ret.getLongDouble()); };
1977 break;
1978 }
1979 //
1980 // Language-Specific Types
1981 //
1982 case BuiltinType::NullPtr:
1983 // C++11 nullptr
1984 ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1985 "Invalid type 'nullptr'!");
1986 return {};
1987 break;
1988 default:
1989 break;
1990 }
1991 return {};
1992}
1993
1994
1996TClingCallFunc::InitRetAndExecNoCtor(clang::QualType QT, cling::Value &ret) {
1997 if (QT->isReferenceType()) {
1998 ret = cling::Value(QT, *fInterp);
1999 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2000 } else if (QT->isMemberPointerType()) {
2001 const MemberPointerType *MPT = QT->getAs<MemberPointerType>();
2002 if (MPT && MPT->isMemberDataPointer()) {
2003 // A member data pointer is a actually a struct with one
2004 // member of ptrdiff_t, the offset from the base of the object
2005 // storage to the storage for the designated data member.
2006 // But that's not relevant: we use it as a non-builtin, allocated
2007 // type.
2008 ret = cling::Value(QT, *fInterp);
2009 return [this](void* address, cling::Value& ret) { exec(address, ret.getPtr()); };
2010 }
2011 // We are a function member pointer.
2012 ret = cling::Value(QT, *fInterp);
2013 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2014 } else if (QT->isPointerType() || QT->isArrayType()) {
2015 // Note: ArrayType is an illegal function return value type.
2016 ret = cling::Value::Create<void*>(QT.getAsOpaquePtr(), *fInterp);
2017 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2018 } else if (QT->isRecordType()) {
2019 ret = cling::Value(QT, *fInterp);
2020 return [this](void* address, cling::Value& ret) { exec(address, ret.getPtr()); };
2021 } else if (const EnumType *ET = dyn_cast<EnumType>(&*QT)) {
2022 // Note: We may need to worry about the underlying type
2023 // of the enum here.
2024 (void) ET;
2025 ret = cling::Value(QT, *fInterp);
2026 return [this](void* address, cling::Value& ret) { execWithLL<int>(address, &ret); };
2027 } else if (const BuiltinType *BT = dyn_cast<BuiltinType>(&*QT)) {
2028 return InitRetAndExecBuiltin(QT, BT, ret);
2029 }
2030 ::Error("TClingCallFunc::exec_with_valref_return",
2031 "Unrecognized return type!");
2032 QT->dump();
2033 return {};
2034}
2035
2037TClingCallFunc::InitRetAndExec(const clang::FunctionDecl *FD, cling::Value &ret) {
2038 if (llvm::isa<CXXConstructorDecl>(FD)) {
2039 ASTContext &Context = FD->getASTContext();
2040 const TypeDecl *TD = dyn_cast<TypeDecl>(GetDeclContext());
2041 QualType ClassTy(TD->getTypeForDecl(), 0);
2042 QualType QT = Context.getLValueReferenceType(ClassTy);
2043 ret = cling::Value(QT, *fInterp);
2044 // Store the new()'ed address in getPtr()
2045 return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2046 } else {
2047 QualType QT = FD->getReturnType().getCanonicalType();
2048 return InitRetAndExecNoCtor(QT, ret);
2049 }
2050}
2051
2052void TClingCallFunc::exec_with_valref_return(void *address, cling::Value *ret)
2053{
2054 if (!ret) {
2055 exec(address, 0);
2056 return;
2057 }
2058 std::function<void(void*, cling::Value&)> execFunc;
2059
2060 /* Release lock during user function execution*/
2061 {
2063 execFunc = InitRetAndExec(GetDecl(), *ret);
2064 }
2065
2066 if (execFunc)
2067 execFunc(address, *ret);
2068 return;
2069}
2070
2071void TClingCallFunc::EvaluateArgList(const string &ArgList)
2072{
2074
2075 SmallVector<Expr *, 4> exprs;
2076 fInterp->getLookupHelper().findArgList(ArgList, exprs,
2077 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
2078 : cling::LookupHelper::NoDiagnostics);
2079 for (SmallVectorImpl<Expr *>::const_iterator I = exprs.begin(),
2080 E = exprs.end(); I != E; ++I) {
2081 cling::Value val;
2082 EvaluateExpr(*fInterp, *I, val);
2083 if (!val.isValid()) {
2084 // Bad expression, all done.
2085 ::Error("TClingCallFunc::EvaluateArgList",
2086 "Bad expression in parameter %d of '%s'!",
2087 (int)(I - exprs.begin()),
2088 ArgList.c_str());
2089 return;
2090 }
2091 fArgVals.push_back(val);
2092 }
2093}
2094
2095void TClingCallFunc::Exec(void *address, TInterpreterValue *interpVal/*=0*/)
2096{
2097 IFacePtr();
2098 if (!fWrapper) {
2099 ::Error("TClingCallFunc::Exec(address, interpVal)",
2100 "Called with no wrapper, not implemented!");
2101 return;
2102 }
2103 if (!interpVal) {
2104 exec(address, 0);
2105 return;
2106 }
2107 cling::Value *val = reinterpret_cast<cling::Value *>(interpVal->GetValAddr());
2108 exec_with_valref_return(address, val);
2109}
2110
2111template <typename T>
2113{
2114 IFacePtr();
2115 if (!fWrapper) {
2116 ::Error("TClingCallFunc::ExecT",
2117 "Called with no wrapper, not implemented!");
2118 return 0;
2119 }
2120 cling::Value ret;
2121 exec_with_valref_return(address, &ret);
2122 if (!ret.isValid()) {
2123 // Sometimes we are called on a function returning void!
2124 return 0;
2125 }
2126
2128 ((TCling *)gCling)->RegisterTemporary(ret);
2129 return sv_to<T>(ret);
2130}
2131
2133{
2134 return ExecT<Longptr_t>(address);
2135}
2136
2137long long TClingCallFunc::ExecInt64(void *address)
2138{
2139 return ExecT<long long>(address);
2140}
2141
2142double TClingCallFunc::ExecDouble(void *address)
2143{
2144 return ExecT<double>(address);
2145}
2146
2147void TClingCallFunc::ExecWithArgsAndReturn(void *address, const void *args[] /*= 0*/,
2148 int nargs /*= 0*/, void *ret/*= 0*/)
2149{
2150 IFacePtr();
2151 if (!fWrapper) {
2152 ::Error("TClingCallFunc::ExecWithArgsAndReturn(address, args, ret)",
2153 "Called with no wrapper, not implemented!");
2154 return;
2155 }
2156 (*fWrapper)(address, nargs, const_cast<void **>(args), ret);
2157}
2158
2159void TClingCallFunc::ExecWithReturn(void *address, void *ret/*= 0*/)
2160{
2161 IFacePtr();
2162 if (!fWrapper) {
2163 ::Error("TClingCallFunc::ExecWithReturn(address, ret)",
2164 "Called with no wrapper, not implemented!");
2165 return;
2166 }
2167 exec(address, ret);
2168}
2169
2172 const std::string &type_name,
2173 void *address /*=0*/, unsigned long nary /*= 0UL*/)
2174{
2175 if (!info->IsValid()) {
2176 ::Error("TClingCallFunc::ExecDefaultConstructor", "Invalid class info!");
2177 return nullptr;
2178 }
2179 tcling_callfunc_ctor_Wrapper_t wrapper = nullptr;
2180 {
2182 auto D = info->GetDecl();
2183 //if (!info->HasDefaultConstructor()) {
2184 // // FIXME: We might have a ROOT ioctor, we might
2185 // // have to check for that here.
2186 // ::Error("TClingCallFunc::ExecDefaultConstructor",
2187 // "Class has no default constructor: %s",
2188 // info->Name());
2189 // return 0;
2190 //}
2191 auto I = gCtorWrapperStore.find(D);
2192 if (I != gCtorWrapperStore.end()) {
2193 wrapper = (tcling_callfunc_ctor_Wrapper_t) I->second;
2194 } else {
2195 wrapper = make_ctor_wrapper(info, kind, type_name);
2196 }
2197 }
2198 if (!wrapper) {
2199 ::Error("TClingCallFunc::ExecDefaultConstructor",
2200 "Called with no wrapper, not implemented!");
2201 return nullptr;
2202 }
2203 void *obj = 0;
2204 (*wrapper)(&obj, address, nary);
2205 return obj;
2206}
2207
2208void TClingCallFunc::ExecDestructor(const TClingClassInfo *info, void *address /*=0*/,
2209 unsigned long nary /*= 0UL*/, bool withFree /*= true*/)
2210{
2211 if (!info->IsValid()) {
2212 ::Error("TClingCallFunc::ExecDestructor", "Invalid class info!");
2213 return;
2214 }
2215
2217 {
2219 const Decl *D = info->GetDecl();
2220 map<const Decl *, void *>::iterator I = gDtorWrapperStore.find(D);
2221 if (I != gDtorWrapperStore.end()) {
2222 wrapper = (tcling_callfunc_dtor_Wrapper_t) I->second;
2223 } else {
2224 wrapper = make_dtor_wrapper(info);
2225 }
2226 }
2227 if (!wrapper) {
2228 ::Error("TClingCallFunc::ExecDestructor",
2229 "Called with no wrapper, not implemented!");
2230 return;
2231 }
2232 (*wrapper)(address, nary, withFree);
2233}
2234
2237{
2238 return new TClingMethodInfo(*fMethod);
2239}
2240
2242{
2243 fMethod.reset();
2244 fWrapper = 0;
2245 fDecl = nullptr;
2247 ResetArg();
2248}
2249
2251{
2252 Init();
2253 fMethod = std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(minfo));
2254}
2255
2256void TClingCallFunc::Init(std::unique_ptr<TClingMethodInfo> minfo)
2257{
2258 Init();
2259 fMethod = std::move(minfo);
2260}
2261
2263{
2264 if (!IsValid()) {
2265 return 0;
2266 }
2267 if (!fWrapper) {
2268 const Decl *decl = GetFunctionOrShadowDecl();
2269
2271 map<const Decl *, void *>::iterator I = gWrapperStore.find(decl);
2272 if (I != gWrapperStore.end()) {
2274 } else {
2276 }
2277 }
2278 return (void *)fWrapper;
2279}
2280
2282{
2283 if (!fMethod) {
2284 return false;
2285 }
2286 return fMethod->IsValid();
2287}
2288
2290{
2291 if (!IsValid()) {
2292 ::Error("TClingCallFunc::IFacePtr(kind)",
2293 "Attempt to get interface while invalid.");
2295 }
2296 if (!fWrapper) {
2297 const Decl *decl = GetFunctionOrShadowDecl();
2298
2300 map<const Decl *, void *>::iterator I = gWrapperStore.find(decl);
2301 if (I != gWrapperStore.end()) {
2303 } else {
2305 }
2306
2307 fReturnIsRecordType = GetDecl()->getReturnType().getCanonicalType()->isRecordType();
2308 }
2310}
2311
2312
2314{
2315 fArgVals.clear();
2316}
2317
2318void TClingCallFunc::SetArg(unsigned long param)
2319{
2320 const ASTContext &C = fInterp->getCI()->getASTContext();
2321 fArgVals.push_back(cling::Value(C.UnsignedLongTy, *fInterp));
2322 fArgVals.back().getLL() = param;
2323}
2324
2326{
2327 const ASTContext &C = fInterp->getCI()->getASTContext();
2328 fArgVals.push_back(cling::Value(C.LongTy, *fInterp));
2329 fArgVals.back().getLL() = param;
2330}
2331
2332void TClingCallFunc::SetArg(float param)
2333{
2334 const ASTContext &C = fInterp->getCI()->getASTContext();
2335 fArgVals.push_back(cling::Value(C.FloatTy, *fInterp));
2336 fArgVals.back().getFloat() = param;
2337}
2338
2339void TClingCallFunc::SetArg(double param)
2340{
2341 const ASTContext &C = fInterp->getCI()->getASTContext();
2342 fArgVals.push_back(cling::Value(C.DoubleTy, *fInterp));
2343 fArgVals.back().getDouble() = param;
2344}
2345
2346void TClingCallFunc::SetArg(long long param)
2347{
2348 const ASTContext &C = fInterp->getCI()->getASTContext();
2349 fArgVals.push_back(cling::Value(C.LongLongTy, *fInterp));
2350 fArgVals.back().getLL() = param;
2351}
2352
2353void TClingCallFunc::SetArg(unsigned long long param)
2354{
2355 const ASTContext &C = fInterp->getCI()->getASTContext();
2356 fArgVals.push_back(cling::Value(C.UnsignedLongLongTy, *fInterp));
2357 fArgVals.back().getULL() = param;
2358}
2359
2360void TClingCallFunc::SetArgArray(Longptr_t *paramArr, int nparam)
2361{
2362 ResetArg();
2363 for (int i = 0; i < nparam; ++i) {
2364 SetArg(paramArr[i]);
2365 }
2366}
2367
2368void TClingCallFunc::SetArgs(const char *params)
2369{
2370 ResetArg();
2371 EvaluateArgList(params);
2372}
2373
2374void TClingCallFunc::SetFunc(const TClingClassInfo *info, const char *method, const char *arglist,
2375 Longptr_t *poffset)
2376{
2377 SetFunc(info, method, arglist, false, poffset);
2378}
2379
2380void TClingCallFunc::SetFunc(const TClingClassInfo *info, const char *method, const char *arglist,
2381 bool objectIsConst, Longptr_t *poffset)
2382{
2383 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2384 if (poffset) {
2385 *poffset = 0L;
2386 }
2387 ResetArg();
2388 if (!info->IsValid()) {
2389 ::Error("TClingCallFunc::SetFunc", "Class info is invalid!");
2390 return;
2391 }
2392 if (!strcmp(arglist, ")")) {
2393 // CINT accepted a single right paren as meaning no arguments.
2394 arglist = "";
2395 }
2396 *fMethod = info->GetMethodWithArgs(method, arglist, objectIsConst, poffset);
2397 if (!fMethod->IsValid()) {
2398 //::Error("TClingCallFunc::SetFunc", "Could not find method %s(%s)", method,
2399 // arglist);
2400 return;
2401 }
2402 // FIXME: The arglist was already parsed by the lookup, we should
2403 // enhance the lookup to return the resulting expression
2404 // list so we do not need to parse it again here.
2405 EvaluateArgList(arglist);
2406}
2407
2409{
2410 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(*info)));
2411 ResetArg();
2412 if (!fMethod->IsValid()) {
2413 return;
2414 }
2415}
2416
2417void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2418 const char *proto, Longptr_t *poffset,
2419 EFunctionMatchMode mode/*=kConversionMatch*/)
2420{
2421 SetFuncProto(info, method, proto, false, poffset, mode);
2422}
2423
2424void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2425 const char *proto, bool objectIsConst, Longptr_t *poffset,
2426 EFunctionMatchMode mode/*=kConversionMatch*/)
2427{
2428 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2429 if (poffset) {
2430 *poffset = 0L;
2431 }
2432 ResetArg();
2433 if (!info->IsValid()) {
2434 ::Error("TClingCallFunc::SetFuncProto", "Class info is invalid!");
2435 return;
2436 }
2437 *fMethod = info->GetMethod(method, proto, objectIsConst, poffset, mode);
2438 if (!fMethod->IsValid()) {
2439 //::Error("TClingCallFunc::SetFuncProto", "Could not find method %s(%s)",
2440 // method, proto);
2441 return;
2442 }
2443}
2444
2445void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2446 const llvm::SmallVectorImpl<clang::QualType> &proto, Longptr_t *poffset,
2447 EFunctionMatchMode mode/*=kConversionMatch*/)
2448{
2449 SetFuncProto(info, method, proto, false, poffset, mode);
2450}
2451
2452void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2453 const llvm::SmallVectorImpl<clang::QualType> &proto,
2454 bool objectIsConst, Longptr_t *poffset,
2455 EFunctionMatchMode mode/*=kConversionMatch*/)
2456{
2457 Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2458 if (poffset) {
2459 *poffset = 0L;
2460 }
2461 ResetArg();
2462 if (!info->IsValid()) {
2463 ::Error("TClingCallFunc::SetFuncProto", "Class info is invalid!");
2464 return;
2465 }
2466 *fMethod = info->GetMethod(method, proto, objectIsConst, poffset, mode);
2467 if (!fMethod->IsValid()) {
2468 //::Error("TClingCallFunc::SetFuncProto", "Could not find method %s(%s)",
2469 // method, proto);
2470 return;
2471 }
2472}
2473
l unsigned short
long
typedef void(GLAPIENTRYP _GLUfuncptr)(void)
long Longptr_t
Definition RtypesCore.h:82
static void EvaluateExpr(cling::Interpreter &interp, const Expr *E, cling::Value &V)
static unsigned long long gWrapperSerial
static map< const Decl *, void * > gCtorWrapperStore
static const string kIndentString(" ")
static void indent(ostringstream &buf, int indent_level)
static map< const Decl *, void * > gDtorWrapperStore
static map< const Decl *, void * > gWrapperStore
void(* tcling_callfunc_ctor_Wrapper_t)(void **, void *, unsigned long)
void(* tcling_callfunc_Wrapper_t)(void *, int, void **, void *)
void(* tcling_callfunc_dtor_Wrapper_t)(void *, unsigned long, int)
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:187
#define N
char name[80]
Definition TGX11.cxx:110
R__EXTERN TVirtualMutex * gInterpreterMutex
#define R__LOCKGUARD_CLING(mutex)
R__EXTERN TInterpreter * gCling
Int_t gDebug
Definition TROOT.cxx:592
const char * proto
Definition civetweb.c:16613
void * ExecDefaultConstructor(const TClingClassInfo *info, ROOT::TMetaUtils::EIOCtorCategory kind, const std::string &type_name, void *address=nullptr, unsigned long nary=0UL)
void ExecWithReturn(void *address, void *ret=nullptr)
std::unique_ptr< TClingMethodInfo > fMethod
Current method, we own.
ExecWithRetFunc_t InitRetAndExec(const clang::FunctionDecl *FD, cling::Value &ret)
void collect_type_info(clang::QualType &QT, std::ostringstream &typedefbuf, std::ostringstream &callbuf, std::string &type_name, EReferenceType &refType, bool &isPointer, int indent_level, bool forArgument)
void SetArgs(const char *args)
size_t fMinRequiredArguments
Number of required arguments.
T ExecT(void *address)
size_t CalculateMinRequiredArguments()
double ExecDouble(void *address)
void SetArgArray(Longptr_t *argArr, int narg)
tcling_callfunc_Wrapper_t make_wrapper()
ExecWithRetFunc_t InitRetAndExecNoCtor(clang::QualType QT, cling::Value &ret)
bool IsValid() const
tcling_callfunc_dtor_Wrapper_t make_dtor_wrapper(const TClingClassInfo *info)
std::function< void(void *address, cling::Value &ret)> ExecWithRetFunc_t
void ExecDestructor(const TClingClassInfo *info, void *address=nullptr, unsigned long nary=0UL, bool withFree=true)
Longptr_t ExecInt(void *address)
void execWithLL(void *address, cling::Value *val)
const clang::DeclContext * GetDeclContext() const
void * compile_wrapper(const std::string &wrapper_name, const std::string &wrapper, bool withAccessControl=true)
void SetFuncProto(const TClingClassInfo *info, const char *method, const char *proto, Longptr_t *poffset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
TInterpreter::CallFuncIFacePtr_t IFacePtr()
void exec(void *address, void *ret)
void exec_with_valref_return(void *address, cling::Value *ret)
void make_narg_ctor(const unsigned N, std::ostringstream &typedefbuf, std::ostringstream &callbuf, const std::string &class_name, int indent_level)
void SetFunc(const TClingClassInfo *info, const char *method, const char *arglist, Longptr_t *poffset)
const clang::FunctionDecl * GetDecl()
void execWithULL(void *address, cling::Value *val)
void EvaluateArgList(const std::string &ArgList)
const clang::Decl * GetFunctionOrShadowDecl() const
void ExecWithArgsAndReturn(void *address, const void *args[]=0, int nargs=0, void *ret=0)
void Exec(void *address, TInterpreterValue *interpVal=0)
TClingMethodInfo * FactoryMethod() const
ExecWithRetFunc_t InitRetAndExecIntegral(clang::QualType QT, cling::Value &ret)
int get_wrapper_code(std::string &wrapper_name, std::string &wrapper)
size_t GetMinRequiredArguments()
tcling_callfunc_ctor_Wrapper_t make_ctor_wrapper(const TClingClassInfo *, ROOT::TMetaUtils::EIOCtorCategory, const std::string &)
const ROOT::TMetaUtils::TNormalizedCtxt & fNormCtxt
ROOT normalized context for that interpreter.
tcling_callfunc_Wrapper_t fWrapper
Pointer to compiled wrapper, we do not own.
long long ExecInt64(void *address)
cling::Interpreter * fInterp
Cling interpreter, we do not own.
void make_narg_call(const std::string &return_type, const unsigned N, std::ostringstream &typedefbuf, std::ostringstream &callbuf, const std::string &class_name, int indent_level)
void SetArg(long arg)
const clang::FunctionDecl * fDecl
Decl for the method.
void make_narg_call_with_return(const unsigned N, const std::string &class_name, std::ostringstream &buf, int indent_level)
llvm::SmallVector< cling::Value, 8 > fArgVals
Stored function arguments, we own.
void make_narg_ctor_with_return(const unsigned N, const std::string &class_name, std::ostringstream &buf, int indent_level)
ExecWithRetFunc_t InitRetAndExecBuiltin(clang::QualType QT, const clang::BuiltinType *BT, cling::Value &ret)
Emulation of the CINT ClassInfo class.
TClingMethodInfo GetMethodWithArgs(const char *fname, const char *arglist, Longptr_t *poffset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch, EInheritanceMode imode=kWithInheritance) const
TClingMethodInfo GetMethod(const char *fname) const
virtual bool IsValid() const
virtual const clang::Decl * GetDecl() const
Emulation of the CINT MethodInfo class.
This class defines an interface to the cling C++ interpreter.
Definition TCling.h:102
virtual const void * GetValAddr() const =0
long double ldbl
unsigned long ul
union ValHolder::@28 u
unsigned long long ull
unsigned int ui
signed char sc
unsigned short us
unsigned char uc
#define F(x, y, z)
#define I(x, y, z)
void GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
Return the type name normalized for ROOT, keeping only the ROOT opaque typedef (Double32_t,...
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
EFunctionMatchMode