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