Logo ROOT   master
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
15 Emulation of the CINT CallFunc class.
16 
17 The CINT C++ interpreter provides an interface for calling
18 functions through the generated wrappers in dictionaries with
19 the CallFunc class. This class provides the same functionality,
20 using an interface as close as possible to CallFunc but the
21 function metadata and calling service comes from the Cling
22 C++ 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 
74 using namespace ROOT;
75 using namespace llvm;
76 using namespace clang;
77 using namespace std;
78 
79 static unsigned long long gWrapperSerial = 0LL;
80 static const string kIndentString(" ");
81 
82 static map<const FunctionDecl *, void *> gWrapperStore;
83 static map<const Decl *, void *> gCtorWrapperStore;
84 static map<const Decl *, void *> gDtorWrapperStore;
85 
86 static
87 inline
88 void
89 indent(ostringstream &buf, int indent_level)
90 {
91  for (int i = 0; i < indent_level; ++i) {
92  buf << kIndentString;
93  }
94 }
95 
96 static
97 void
98 EvaluateExpr(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 
130 namespace {
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  //
152  case BuiltinType::Bool:
153  case BuiltinType::Char_U: // char on targets where it is unsigned
154  case BuiltinType::UChar:
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:
167  case BuiltinType::UShort:
168  case BuiltinType::UInt:
169  case BuiltinType::ULong:
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 
193  case BuiltinType::Short:
194  case BuiltinType::Int:
195  case BuiltinType::Long:
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 
207  case BuiltinType::Float:
208  return (returnType) val.getFloat();
209  break;
210  case BuiltinType::Double:
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 
266 void *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 
273 void 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) {
285  ROOT::TMetaUtils::GetNormalizedName(type_name, QT, *fInterp, fNormCtxt);
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  }
343  ROOT::TMetaUtils::GetNormalizedName(type_name, QT, *fInterp, fNormCtxt);
344 }
345 
346 void 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;
362  EReferenceType refType = kNotReference;
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 
391 void 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;
435  ROOT::TMetaUtils::GetNormalizedName(arg_type, QT, *fInterp, fNormCtxt);
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>(FD->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;
475  EReferenceType refType = kNotReference;
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 
507 void 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 int TClingCallFunc::get_wrapper_code(std::string &wrapper_name, std::string &wrapper)
583 {
584  const FunctionDecl *FD = GetDecl();
585  assert(FD && "generate_wrapper called without a function decl!");
586  ASTContext &Context = FD->getASTContext();
587  PrintingPolicy Policy(Context.getPrintingPolicy());
588  //
589  // Get the class or namespace name.
590  //
591  string class_name;
592  if (const TypeDecl *TD = dyn_cast<TypeDecl>(FD->getDeclContext())) {
593  // This is a class, struct, or union member.
594  QualType QT(TD->getTypeForDecl(), 0);
595  ROOT::TMetaUtils::GetNormalizedName(class_name, QT, *fInterp, fNormCtxt);
596  } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(FD->getDeclContext())) {
597  // This is a namespace member.
598  raw_string_ostream stream(class_name);
599  ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
600  stream.flush();
601  }
602  //
603  // Check to make sure that we can
604  // instantiate and codegen this function.
605  //
606  bool needInstantiation = false;
607  const FunctionDecl *Definition = 0;
608  if (!FD->isDefined(Definition)) {
609  FunctionDecl::TemplatedKind TK = FD->getTemplatedKind();
610  switch (TK) {
611  case FunctionDecl::TK_NonTemplate: {
612  // Ordinary function, not a template specialization.
613  // Note: This might be ok, the body might be defined
614  // in a library, and all we have seen is the
615  // header file.
616  //::Error("TClingCallFunc::make_wrapper",
617  // "Cannot make wrapper for a function which is "
618  // "declared but not defined!");
619  // return 0;
620  } break;
621  case FunctionDecl::TK_FunctionTemplate: {
622  // This decl is actually a function template,
623  // not a function at all.
624  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template!");
625  return 0;
626  } break;
627  case FunctionDecl::TK_MemberSpecialization: {
628  // This function is the result of instantiating an ordinary
629  // member function of a class template, or of instantiating
630  // an ordinary member function of a class member of a class
631  // template, or of specializing a member function template
632  // of a class template, or of specializing a member function
633  // template of a class member of a class template.
634  if (!FD->isTemplateInstantiation()) {
635  // We are either TSK_Undeclared or
636  // TSK_ExplicitSpecialization.
637  // Note: This might be ok, the body might be defined
638  // in a library, and all we have seen is the
639  // header file.
640  //::Error("TClingCallFunc::make_wrapper",
641  // "Cannot make wrapper for a function template "
642  // "explicit specialization which is declared "
643  // "but not defined!");
644  // return 0;
645  break;
646  }
647  const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
648  if (!Pattern) {
649  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a member function "
650  "instantiation with no pattern!");
651  return 0;
652  }
653  FunctionDecl::TemplatedKind PTK = Pattern->getTemplatedKind();
654  TemplateSpecializationKind PTSK = Pattern->getTemplateSpecializationKind();
655  if (
656  // The pattern is an ordinary member function.
657  (PTK == FunctionDecl::TK_NonTemplate) ||
658  // The pattern is an explicit specialization, and
659  // so is not a template.
660  ((PTK != FunctionDecl::TK_FunctionTemplate) &&
661  ((PTSK == TSK_Undeclared) || (PTSK == TSK_ExplicitSpecialization)))) {
662  // Note: This might be ok, the body might be defined
663  // in a library, and all we have seen is the
664  // header file.
665  break;
666  } else if (!Pattern->hasBody()) {
667  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a member function "
668  "instantiation with no body!");
669  return 0;
670  }
671  if (FD->isImplicitlyInstantiable()) {
672  needInstantiation = true;
673  }
674  } break;
675  case FunctionDecl::TK_FunctionTemplateSpecialization: {
676  // This function is the result of instantiating a function
677  // template or possibly an explicit specialization of a
678  // function template. Could be a namespace scope function or a
679  // member function.
680  if (!FD->isTemplateInstantiation()) {
681  // We are either TSK_Undeclared or
682  // TSK_ExplicitSpecialization.
683  // Note: This might be ok, the body might be defined
684  // in a library, and all we have seen is the
685  // header file.
686  //::Error("TClingCallFunc::make_wrapper",
687  // "Cannot make wrapper for a function template "
688  // "explicit specialization which is declared "
689  // "but not defined!");
690  // return 0;
691  break;
692  }
693  const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
694  if (!Pattern) {
695  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template"
696  "instantiation with no pattern!");
697  return 0;
698  }
699  FunctionDecl::TemplatedKind PTK = Pattern->getTemplatedKind();
700  TemplateSpecializationKind PTSK = Pattern->getTemplateSpecializationKind();
701  if (
702  // The pattern is an ordinary member function.
703  (PTK == FunctionDecl::TK_NonTemplate) ||
704  // The pattern is an explicit specialization, and
705  // so is not a template.
706  ((PTK != FunctionDecl::TK_FunctionTemplate) &&
707  ((PTSK == TSK_Undeclared) || (PTSK == TSK_ExplicitSpecialization)))) {
708  // Note: This might be ok, the body might be defined
709  // in a library, and all we have seen is the
710  // header file.
711  break;
712  }
713  if (!Pattern->hasBody()) {
714  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template"
715  "instantiation with no body!");
716  return 0;
717  }
718  if (FD->isImplicitlyInstantiable()) {
719  needInstantiation = true;
720  }
721  } break;
722  case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
723  // This function is the result of instantiating or
724  // specializing a member function of a class template,
725  // or a member function of a class member of a class template,
726  // or a member function template of a class template, or a
727  // member function template of a class member of a class
728  // template where at least some part of the function is
729  // dependent on a template argument.
730  if (!FD->isTemplateInstantiation()) {
731  // We are either TSK_Undeclared or
732  // TSK_ExplicitSpecialization.
733  // Note: This might be ok, the body might be defined
734  // in a library, and all we have seen is the
735  // header file.
736  //::Error("TClingCallFunc::make_wrapper",
737  // "Cannot make wrapper for a dependent function "
738  // "template explicit specialization which is declared "
739  // "but not defined!");
740  // return 0;
741  break;
742  }
743  const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
744  if (!Pattern) {
745  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a dependent function template"
746  "instantiation with no pattern!");
747  return 0;
748  }
749  FunctionDecl::TemplatedKind PTK = Pattern->getTemplatedKind();
750  TemplateSpecializationKind PTSK = Pattern->getTemplateSpecializationKind();
751  if (
752  // The pattern is an ordinary member function.
753  (PTK == FunctionDecl::TK_NonTemplate) ||
754  // The pattern is an explicit specialization, and
755  // so is not a template.
756  ((PTK != FunctionDecl::TK_FunctionTemplate) &&
757  ((PTSK == TSK_Undeclared) || (PTSK == TSK_ExplicitSpecialization)))) {
758  // Note: This might be ok, the body might be defined
759  // in a library, and all we have seen is the
760  // header file.
761  break;
762  }
763  if (!Pattern->hasBody()) {
764  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a dependent function template"
765  "instantiation with no body!");
766  return 0;
767  }
768  if (FD->isImplicitlyInstantiable()) {
769  needInstantiation = true;
770  }
771  } break;
772  default: {
773  // Will only happen if clang implementation changes.
774  // Protect ourselves in case that happens.
775  ::Error("TClingCallFunc::make_wrapper", "Unhandled template kind!");
776  return 0;
777  } break;
778  }
779  // We do not set needInstantiation to true in these cases:
780  //
781  // isInvalidDecl()
782  // TSK_Undeclared
783  // TSK_ExplicitInstantiationDefinition
784  // TSK_ExplicitSpecialization && !getClassScopeSpecializationPattern()
785  // TSK_ExplicitInstantiationDeclaration &&
786  // getTemplateInstantiationPattern() &&
787  // PatternDecl->hasBody() &&
788  // !PatternDecl->isInlined()
789  //
790  // Set it true in these cases:
791  //
792  // TSK_ImplicitInstantiation
793  // TSK_ExplicitInstantiationDeclaration && (!getPatternDecl() ||
794  // !PatternDecl->hasBody() || PatternDecl->isInlined())
795  //
796  }
797  if (needInstantiation) {
798  clang::FunctionDecl *FDmod = const_cast<clang::FunctionDecl *>(FD);
799  clang::Sema &S = fInterp->getSema();
800  // Could trigger deserialization of decls.
801  cling::Interpreter::PushTransactionRAII RAII(fInterp);
802  S.InstantiateFunctionDefinition(SourceLocation(), FDmod,
803  /*Recursive=*/true,
804  /*DefinitionRequired=*/true);
805  if (!FD->isDefined(Definition)) {
806  ::Error("TClingCallFunc::make_wrapper", "Failed to force template instantiation!");
807  return 0;
808  }
809  }
810  if (Definition) {
811  FunctionDecl::TemplatedKind TK = Definition->getTemplatedKind();
812  switch (TK) {
813  case FunctionDecl::TK_NonTemplate: {
814  // Ordinary function, not a template specialization.
815  if (Definition->isDeleted()) {
816  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted function!");
817  return 0;
818  } else if (Definition->isLateTemplateParsed()) {
819  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
820  "function!");
821  return 0;
822  }
823  // else if (Definition->isDefaulted()) {
824  // // Might not have a body, but we can still use it.
825  //}
826  // else {
827  // // Has a body.
828  //}
829  } break;
830  case FunctionDecl::TK_FunctionTemplate: {
831  // This decl is actually a function template,
832  // not a function at all.
833  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a function template!");
834  return 0;
835  } break;
836  case FunctionDecl::TK_MemberSpecialization: {
837  // This function is the result of instantiating an ordinary
838  // member function of a class template or of a member class
839  // of a class template.
840  if (Definition->isDeleted()) {
841  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted member function "
842  "of a specialization!");
843  return 0;
844  } else if (Definition->isLateTemplateParsed()) {
845  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
846  "member function of a specialization!");
847  return 0;
848  }
849  // else if (Definition->isDefaulted()) {
850  // // Might not have a body, but we can still use it.
851  //}
852  // else {
853  // // Has a body.
854  //}
855  } break;
856  case FunctionDecl::TK_FunctionTemplateSpecialization: {
857  // This function is the result of instantiating a function
858  // template or possibly an explicit specialization of a
859  // function template. Could be a namespace scope function or a
860  // member function.
861  if (Definition->isDeleted()) {
862  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted function "
863  "template specialization!");
864  return 0;
865  } else if (Definition->isLateTemplateParsed()) {
866  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
867  "function template specialization!");
868  return 0;
869  }
870  // else if (Definition->isDefaulted()) {
871  // // Might not have a body, but we can still use it.
872  //}
873  // else {
874  // // Has a body.
875  //}
876  } break;
877  case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
878  // This function is the result of instantiating or
879  // specializing a member function of a class template,
880  // or a member function of a class member of a class template,
881  // or a member function template of a class template, or a
882  // member function template of a class member of a class
883  // template where at least some part of the function is
884  // dependent on a template argument.
885  if (Definition->isDeleted()) {
886  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a deleted dependent function "
887  "template specialization!");
888  return 0;
889  } else if (Definition->isLateTemplateParsed()) {
890  ::Error("TClingCallFunc::make_wrapper", "Cannot make wrapper for a late template parsed "
891  "dependent function template specialization!");
892  return 0;
893  }
894  // else if (Definition->isDefaulted()) {
895  // // Might not have a body, but we can still use it.
896  //}
897  // else {
898  // // Has a body.
899  //}
900  } break;
901  default: {
902  // Will only happen if clang implementation changes.
903  // Protect ourselves in case that happens.
904  ::Error("TClingCallFunc::make_wrapper", "Unhandled template kind!");
905  return 0;
906  } break;
907  }
908  }
909  unsigned min_args = GetMinRequiredArguments();
910  unsigned num_params = FD->getNumParams();
911  //
912  // Make the wrapper name.
913  //
914  {
915  ostringstream buf;
916  buf << "__cf";
917  // const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
918  // string mn;
919  // fInterp->maybeMangleDeclName(ND, mn);
920  // buf << '_' << mn;
921  buf << '_' << gWrapperSerial++;
922  wrapper_name = buf.str();
923  }
924  //
925  // Write the wrapper code.
926  // FIXME: this should be synthesized into the AST!
927  //
928  int indent_level = 0;
929  ostringstream buf;
930  buf << "#pragma clang diagnostic push\n"
931  "#pragma clang diagnostic ignored \"-Wformat-security\"\n"
932  "__attribute__((used)) "
933  "extern \"C\" void ";
934  buf << wrapper_name;
935  buf << "(void* obj, int nargs, void** args, void* ret)\n"
936  "{\n";
937  ++indent_level;
938  if (min_args == num_params) {
939  // No parameters with defaults.
940  make_narg_call_with_return(num_params, class_name, buf, indent_level);
941  } else {
942  // We need one function call clause compiled for every
943  // possible number of arguments per call.
944  for (unsigned N = min_args; N <= num_params; ++N) {
945  for (int i = 0; i < indent_level; ++i) {
946  buf << kIndentString;
947  }
948  buf << "if (nargs == " << N << ") {\n";
949  ++indent_level;
950  make_narg_call_with_return(N, class_name, buf, indent_level);
951  --indent_level;
952  for (int i = 0; i < indent_level; ++i) {
953  buf << kIndentString;
954  }
955  buf << "}\n";
956  }
957  }
958  --indent_level;
959  buf << "}\n"
960  "#pragma clang diagnostic pop";
961  wrapper = buf.str();
962  return 1;
963 }
964 
965 void TClingCallFunc::make_narg_call_with_return(const unsigned N, const string &class_name,
966  ostringstream &buf, int indent_level)
967 {
968  // Make a code string that follows this pattern:
969  //
970  // if (ret) {
971  // new (ret) (return_type) ((class_name*)obj)->func(args...);
972  // }
973  // else {
974  // ((class_name*)obj)->func(args...);
975  // }
976  //
977  const FunctionDecl *FD = GetDecl();
978  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
979  (void) CD;
980  make_narg_ctor_with_return(N, class_name, buf, indent_level);
981  return;
982  }
983  QualType QT = FD->getReturnType().getCanonicalType();
984  if (QT->isVoidType()) {
985  ostringstream typedefbuf;
986  ostringstream callbuf;
987  for (int i = 0; i < indent_level; ++i) {
988  callbuf << kIndentString;
989  }
990  make_narg_call("void", N, typedefbuf, callbuf, class_name, indent_level);
991  callbuf << ";\n";
992  for (int i = 0; i < indent_level; ++i) {
993  callbuf << kIndentString;
994  }
995  callbuf << "return;\n";
996  buf << typedefbuf.str() << callbuf.str();
997  } else {
998  for (int i = 0; i < indent_level; ++i) {
999  buf << kIndentString;
1000  }
1001 
1002  string type_name;
1003  EReferenceType refType = kNotReference;
1004  bool isPointer = false;
1005 
1006  buf << "if (ret) {\n";
1007  ++indent_level;
1008  {
1009  ostringstream typedefbuf;
1010  ostringstream callbuf;
1011  //
1012  // Write the placement part of the placement new.
1013  //
1014  for (int i = 0; i < indent_level; ++i) {
1015  callbuf << kIndentString;
1016  }
1017  callbuf << "new (ret) ";
1018  collect_type_info(QT, typedefbuf, callbuf, type_name,
1019  refType, isPointer, indent_level, false);
1020  //
1021  // Write the type part of the placement new.
1022  //
1023  callbuf << "(" << type_name.c_str();
1024  if (refType != kNotReference) {
1025  callbuf << "*) (&";
1026  type_name += "&";
1027  } else if (isPointer) {
1028  callbuf << "*) (";
1029  type_name += "*";
1030  } else {
1031  callbuf << ") (";
1032  }
1033  //
1034  // Write the actual function call.
1035  //
1036  make_narg_call(type_name, N, typedefbuf, callbuf, class_name, indent_level);
1037  //
1038  // End the placement new.
1039  //
1040  callbuf << ");\n";
1041  for (int i = 0; i < indent_level; ++i) {
1042  callbuf << kIndentString;
1043  }
1044  callbuf << "return;\n";
1045  //
1046  // Output the whole placement new expression and return statement.
1047  //
1048  buf << typedefbuf.str() << callbuf.str();
1049  }
1050  --indent_level;
1051  for (int i = 0; i < indent_level; ++i) {
1052  buf << kIndentString;
1053  }
1054  buf << "}\n";
1055  for (int i = 0; i < indent_level; ++i) {
1056  buf << kIndentString;
1057  }
1058  buf << "else {\n";
1059  ++indent_level;
1060  {
1061  ostringstream typedefbuf;
1062  ostringstream callbuf;
1063  for (int i = 0; i < indent_level; ++i) {
1064  callbuf << kIndentString;
1065  }
1066  make_narg_call(type_name, N, typedefbuf, callbuf, class_name, indent_level);
1067  callbuf << ";\n";
1068  for (int i = 0; i < indent_level; ++i) {
1069  callbuf << kIndentString;
1070  }
1071  callbuf << "return;\n";
1072  buf << typedefbuf.str() << callbuf.str();
1073  }
1074  --indent_level;
1075  for (int i = 0; i < indent_level; ++i) {
1076  buf << kIndentString;
1077  }
1078  buf << "}\n";
1079  }
1080 }
1081 
1083 {
1085 
1086  const FunctionDecl *FD = GetDecl();
1087  string wrapper_name;
1088  string wrapper;
1089 
1090  if (get_wrapper_code(wrapper_name, wrapper) == 0) return 0;
1091 
1092  //fprintf(stderr, "%s\n", wrapper.c_str());
1093  //
1094  // Compile the wrapper code.
1095  //
1096  void *F = compile_wrapper(wrapper_name, wrapper);
1097  if (F) {
1098  gWrapperStore.insert(make_pair(FD, F));
1099  } else {
1100  ::Error("TClingCallFunc::make_wrapper",
1101  "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1102  wrapper.c_str());
1103  }
1104  return (tcling_callfunc_Wrapper_t)F;
1105 }
1106 
1108  ROOT::TMetaUtils::EIOCtorCategory kind, const std::string &type_name)
1109 {
1110  // Make a code string that follows this pattern:
1111  //
1112  // void
1113  // unique_wrapper_ddd(void** ret, void* arena, unsigned long nary)
1114  // {
1115  // if (!arena) {
1116  // if (!nary) {
1117  // *ret = new ClassName;
1118  // }
1119  // else {
1120  // *ret = new ClassName[nary];
1121  // }
1122  // }
1123  // else {
1124  // if (!nary) {
1125  // *ret = new (arena) ClassName;
1126  // }
1127  // else {
1128  // *ret = new (arena) ClassName[nary];
1129  // }
1130  // }
1131  // }
1132  //
1133  // When I/O constructor used:
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((TRootIOCtor*)nullptr);
1141  // }
1142  // else {
1143  // char *buf = malloc(nary * sizeof(ClassName));
1144  // for (int k=0;k<nary;++k)
1145  // new (buf + k * sizeof(ClassName)) ClassName((TRootIOCtor*)nullptr);
1146  // *ret = buf;
1147  // }
1148  // }
1149  // else {
1150  // if (!nary) {
1151  // *ret = new (arena) ClassName((TRootIOCtor*)nullptr);
1152  // }
1153  // else {
1154  // for (int k=0;k<nary;++k)
1155  // new ((char *) arena + k * sizeof(ClassName)) ClassName((TRootIOCtor*)nullptr);
1156  // *ret = arena;
1157  // }
1158  // }
1159  // }
1160  //
1161  //
1162  // Note:
1163  //
1164  // If the class is of POD type, the form:
1165  //
1166  // new ClassName;
1167  //
1168  // does not initialize the object at all, and the form:
1169  //
1170  // new ClassName();
1171  //
1172  // default-initializes the object.
1173  //
1174  // We are using the form without parentheses because that is what
1175  // CINT did.
1176  //
1177  //--
1178  ASTContext &Context = info->GetDecl()->getASTContext();
1179  PrintingPolicy Policy(Context.getPrintingPolicy());
1180  Policy.SuppressTagKeyword = true;
1181  Policy.SuppressUnwrittenScope = true;
1182  //
1183  // Get the class or namespace name.
1184  //
1185  string class_name;
1186  if (const TypeDecl *TD = dyn_cast<TypeDecl>(info->GetDecl())) {
1187  // This is a class, struct, or union member.
1188  QualType QT(TD->getTypeForDecl(), 0);
1189  ROOT::TMetaUtils::GetNormalizedName(class_name, QT, *fInterp, fNormCtxt);
1190  } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(info->GetDecl())) {
1191  // This is a namespace member.
1192  raw_string_ostream stream(class_name);
1193  ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
1194  stream.flush();
1195  }
1196 
1197 
1198  //
1199  // Make the wrapper name.
1200  //
1201  string wrapper_name;
1202  {
1203  ostringstream buf;
1204  buf << "__ctor";
1205  //const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
1206  //string mn;
1207  //fInterp->maybeMangleDeclName(ND, mn);
1208  //buf << '_dtor_' << mn;
1209  buf << '_' << gWrapperSerial++;
1210  wrapper_name = buf.str();
1211  }
1212 
1213  string constr_arg;
1215  constr_arg = string("((") + type_name + "*)nullptr)";
1217  constr_arg = string("(*((") + type_name + "*)arena))";
1218 
1219  //
1220  // Write the wrapper code.
1221  //
1222  int indent_level = 0;
1223  ostringstream buf;
1224  buf << "__attribute__((used)) ";
1225  buf << "extern \"C\" void ";
1226  buf << wrapper_name;
1227  buf << "(void** ret, void* arena, unsigned long nary)\n";
1228  buf << "{\n";
1229 
1230  // if (!arena) {
1231  // if (!nary) {
1232  // *ret = new ClassName;
1233  // }
1234  // else {
1235  // *ret = new ClassName[nary];
1236  // }
1237  // }
1238  indent(buf, ++indent_level);
1239  buf << "if (!arena) {\n";
1240  indent(buf, ++indent_level);
1241  buf << "if (!nary) {\n";
1242  indent(buf, ++indent_level);
1243  buf << "*ret = new " << class_name << constr_arg << ";\n";
1244  indent(buf, --indent_level);
1245  buf << "}\n";
1246  indent(buf, indent_level);
1247  buf << "else {\n";
1248  indent(buf, ++indent_level);
1249  if (constr_arg.empty()) {
1250  buf << "*ret = new " << class_name << "[nary];\n";
1251  } else {
1252  buf << "char *buf = (char *) malloc(nary * sizeof(" << class_name << "));\n";
1253  indent(buf, indent_level);
1254  buf << "for (int k=0;k<nary;++k)\n";
1255  indent(buf, ++indent_level);
1256  buf << "new (buf + k * sizeof(" << class_name << ")) " << class_name << constr_arg << ";\n";
1257  indent(buf, --indent_level);
1258  buf << "*ret = buf;\n";
1259  }
1260  indent(buf, --indent_level);
1261  buf << "}\n";
1262  indent(buf, --indent_level);
1263  buf << "}\n";
1264  // else {
1265  // if (!nary) {
1266  // *ret = new (arena) ClassName;
1267  // }
1268  // else {
1269  // *ret = new (arena) ClassName[nary];
1270  // }
1271  // }
1272  indent(buf, indent_level);
1273  buf << "else {\n";
1274  indent(buf, ++indent_level);
1275  buf << "if (!nary) {\n";
1276  indent(buf, ++indent_level);
1277  buf << "*ret = new (arena) " << class_name << constr_arg << ";\n";
1278  indent(buf, --indent_level);
1279  buf << "}\n";
1280  indent(buf, indent_level);
1281  buf << "else {\n";
1282  indent(buf, ++indent_level);
1283  if (constr_arg.empty()) {
1284  buf << "*ret = new (arena) " << class_name << "[nary];\n";
1285  } else {
1286  buf << "for (int k=0;k<nary;++k)\n";
1287  indent(buf, ++indent_level);
1288  buf << "new ((char *) arena + k * sizeof(" << class_name << ")) " << class_name << constr_arg << ";\n";
1289  indent(buf, --indent_level);
1290  buf << "*ret = arena;\n";
1291  }
1292  indent(buf, --indent_level);
1293  buf << "}\n";
1294  indent(buf, --indent_level);
1295  buf << "}\n";
1296  // End wrapper.
1297  --indent_level;
1298  buf << "}\n";
1299  // Done.
1300  string wrapper(buf.str());
1301  //fprintf(stderr, "%s\n", wrapper.c_str());
1302  //
1303  // Compile the wrapper code.
1304  //
1305  void *F = compile_wrapper(wrapper_name, wrapper,
1306  /*withAccessControl=*/false);
1307  if (F) {
1308  gCtorWrapperStore.insert(make_pair(info->GetDecl(), F));
1309  } else {
1310  ::Error("TClingCallFunc::make_ctor_wrapper",
1311  "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1312  wrapper.c_str());
1313  }
1315 }
1316 
1319 {
1320  // Make a code string that follows this pattern:
1321  //
1322  // void
1323  // unique_wrapper_ddd(void* obj, unsigned long nary, int withFree)
1324  // {
1325  // if (withFree) {
1326  // if (!nary) {
1327  // delete (ClassName*) obj;
1328  // }
1329  // else {
1330  // delete[] (ClassName*) obj;
1331  // }
1332  // }
1333  // else {
1334  // typedef ClassName DtorName;
1335  // if (!nary) {
1336  // ((ClassName*)obj)->~DtorName();
1337  // }
1338  // else {
1339  // for (unsigned long i = nary - 1; i > -1; --i) {
1340  // (((ClassName*)obj)+i)->~DtorName();
1341  // }
1342  // }
1343  // }
1344  // }
1345  //
1346  //--
1347  ASTContext &Context = info->GetDecl()->getASTContext();
1348  PrintingPolicy Policy(Context.getPrintingPolicy());
1349  Policy.SuppressTagKeyword = true;
1350  Policy.SuppressUnwrittenScope = true;
1351  //
1352  // Get the class or namespace name.
1353  //
1354  string class_name;
1355  if (const TypeDecl *TD = dyn_cast<TypeDecl>(info->GetDecl())) {
1356  // This is a class, struct, or union member.
1357  QualType QT(TD->getTypeForDecl(), 0);
1358  ROOT::TMetaUtils::GetNormalizedName(class_name, QT, *fInterp, fNormCtxt);
1359  } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(info->GetDecl())) {
1360  // This is a namespace member.
1361  raw_string_ostream stream(class_name);
1362  ND->getNameForDiagnostic(stream, Policy, /*Qualified=*/true);
1363  stream.flush();
1364  }
1365  //
1366  // Make the wrapper name.
1367  //
1368  string wrapper_name;
1369  {
1370  ostringstream buf;
1371  buf << "__dtor";
1372  //const NamedDecl* ND = dyn_cast<NamedDecl>(FD);
1373  //string mn;
1374  //fInterp->maybeMangleDeclName(ND, mn);
1375  //buf << '_dtor_' << mn;
1376  buf << '_' << gWrapperSerial++;
1377  wrapper_name = buf.str();
1378  }
1379  //
1380  // Write the wrapper code.
1381  //
1382  int indent_level = 0;
1383  ostringstream buf;
1384  buf << "__attribute__((used)) ";
1385  buf << "extern \"C\" void ";
1386  buf << wrapper_name;
1387  buf << "(void* obj, unsigned long nary, int withFree)\n";
1388  buf << "{\n";
1389  // if (withFree) {
1390  // if (!nary) {
1391  // delete (ClassName*) obj;
1392  // }
1393  // else {
1394  // delete[] (ClassName*) obj;
1395  // }
1396  // }
1397  ++indent_level;
1398  indent(buf, indent_level);
1399  buf << "if (withFree) {\n";
1400  ++indent_level;
1401  indent(buf, indent_level);
1402  buf << "if (!nary) {\n";
1403  ++indent_level;
1404  indent(buf, indent_level);
1405  buf << "delete (" << class_name << "*) obj;\n";
1406  --indent_level;
1407  indent(buf, indent_level);
1408  buf << "}\n";
1409  indent(buf, indent_level);
1410  buf << "else {\n";
1411  ++indent_level;
1412  indent(buf, indent_level);
1413  buf << "delete[] (" << class_name << "*) obj;\n";
1414  --indent_level;
1415  indent(buf, indent_level);
1416  buf << "}\n";
1417  --indent_level;
1418  indent(buf, indent_level);
1419  buf << "}\n";
1420  // else {
1421  // typedef ClassName Nm;
1422  // if (!nary) {
1423  // ((Nm*)obj)->~Nm();
1424  // }
1425  // else {
1426  // for (unsigned long i = nary - 1; i > -1; --i) {
1427  // (((Nm*)obj)+i)->~Nm();
1428  // }
1429  // }
1430  // }
1431  indent(buf, indent_level);
1432  buf << "else {\n";
1433  ++indent_level;
1434  indent(buf, indent_level);
1435  buf << "typedef " << class_name << " Nm;\n";
1436  buf << "if (!nary) {\n";
1437  ++indent_level;
1438  indent(buf, indent_level);
1439  buf << "((Nm*)obj)->~Nm();\n";
1440  --indent_level;
1441  indent(buf, indent_level);
1442  buf << "}\n";
1443  indent(buf, indent_level);
1444  buf << "else {\n";
1445  ++indent_level;
1446  indent(buf, indent_level);
1447  buf << "do {\n";
1448  ++indent_level;
1449  indent(buf, indent_level);
1450  buf << "(((Nm*)obj)+(--nary))->~Nm();\n";
1451  --indent_level;
1452  indent(buf, indent_level);
1453  buf << "} while (nary);\n";
1454  --indent_level;
1455  indent(buf, indent_level);
1456  buf << "}\n";
1457  --indent_level;
1458  indent(buf, indent_level);
1459  buf << "}\n";
1460  // End wrapper.
1461  --indent_level;
1462  buf << "}\n";
1463  // Done.
1464  string wrapper(buf.str());
1465  //fprintf(stderr, "%s\n", wrapper.c_str());
1466  //
1467  // Compile the wrapper code.
1468  //
1469  void *F = compile_wrapper(wrapper_name, wrapper,
1470  /*withAccessControl=*/false);
1471  if (F) {
1472  gDtorWrapperStore.insert(make_pair(info->GetDecl(), F));
1473  } else {
1474  ::Error("TClingCallFunc::make_dtor_wrapper",
1475  "Failed to compile\n ==== SOURCE BEGIN ====\n%s\n ==== SOURCE END ====",
1476  wrapper.c_str());
1477  }
1478 
1480 }
1481 
1482 class ValHolder {
1483 public:
1484  union {
1485  long double ldbl;
1486  double dbl;
1487  float flt;
1488  //__uint128_t ui128;
1489  //__int128_t i128;
1490  unsigned long long ull;
1491  long long ll;
1492  unsigned long ul;
1493  long l;
1494  unsigned int ui;
1495  int i;
1496  unsigned short us;
1497  short s;
1498  //char32_t c32;
1499  //char16_t c16;
1500  //unsigned wchar_t uwc; - non-standard
1501  wchar_t wc;
1502  unsigned char uc;
1503  signed char sc;
1504  char c;
1505  bool b;
1506  void *vp;
1507  } u;
1508 };
1509 
1510 void TClingCallFunc::exec(void *address, void *ret)
1511 {
1512  SmallVector<ValHolder, 8> vh_ary;
1513  SmallVector<void *, 8> vp_ary;
1514 
1515  unsigned num_args = fArgVals.size();
1516  {
1518 
1519  const FunctionDecl *FD = GetDecl();
1520 
1521  //
1522  // Convert the arguments from cling::Value to their
1523  // actual type and store them in a holder for passing to the
1524  // wrapper function by pointer to value.
1525  //
1526  unsigned num_params = FD->getNumParams();
1527 
1528  if (num_args < GetMinRequiredArguments()) {
1529  ::Error("TClingCallFunc::exec",
1530  "Not enough arguments provided for %s (%d instead of the minimum %d)",
1531  fMethod->Name(),
1532  num_args, (int)GetMinRequiredArguments());
1533  return;
1534  }
1535  if (address == 0 && dyn_cast<CXXMethodDecl>(FD)
1536  && !(dyn_cast<CXXMethodDecl>(FD))->isStatic()
1537  && !dyn_cast<CXXConstructorDecl>(FD)) {
1538  ::Error("TClingCallFunc::exec",
1539  "The method %s is called without an object.",
1540  fMethod->Name());
1541  return;
1542  }
1543  vh_ary.reserve(num_args);
1544  vp_ary.reserve(num_args);
1545  for (unsigned i = 0U; i < num_args; ++i) {
1546  QualType Ty;
1547  if (i < num_params) {
1548  const ParmVarDecl *PVD = FD->getParamDecl(i);
1549  Ty = PVD->getType();
1550  } else {
1551  Ty = fArgVals[i].getType();
1552  }
1553  QualType QT = Ty.getCanonicalType();
1554  if (const BuiltinType *BT =
1555  dyn_cast<BuiltinType>(&*QT)) {
1556  //
1557  // WARNING!!!
1558  //
1559  // This switch is organized in order-of-declaration
1560  // so that the produced assembly code is optimal.
1561  // Do not reorder!
1562  //
1563  switch (BT->getKind()) {
1564  //
1565  // Builtin Types
1566  //
1567  case BuiltinType::Void: {
1568  // void
1569  ::Error("TClingCallFunc::exec(void*)",
1570  "Invalid type 'Void'!");
1571  return;
1572  }
1573  break;
1574  //
1575  // Unsigned Types
1576  //
1577  case BuiltinType::Bool: {
1578  // bool
1579  ValHolder vh;
1580  vh.u.b = (bool) sv_to_ulong_long(fArgVals[i]);
1581  vh_ary.push_back(vh);
1582  vp_ary.push_back(&vh_ary.back());
1583  }
1584  break;
1585  case BuiltinType::Char_U: {
1586  // char on targets where it is unsigned
1587  ValHolder vh;
1588  vh.u.c = (char) sv_to_ulong_long(fArgVals[i]);
1589  vh_ary.push_back(vh);
1590  vp_ary.push_back(&vh_ary.back());
1591  }
1592  break;
1593  case BuiltinType::UChar: {
1594  // unsigned char
1595  ValHolder vh;
1596  vh.u.uc = (unsigned char) sv_to_ulong_long(fArgVals[i]);
1597  vh_ary.push_back(vh);
1598  vp_ary.push_back(&vh_ary.back());
1599  }
1600  break;
1601  case BuiltinType::WChar_U: {
1602  // wchar_t on targets where it is unsigned.
1603  // The standard doesn't allow to specify signednedd of wchar_t
1604  // thus this maps simply to wchar_t.
1605  ValHolder vh;
1606  vh.u.wc = (wchar_t) sv_to_ulong_long(fArgVals[i]);
1607  vh_ary.push_back(vh);
1608  vp_ary.push_back(&vh_ary.back());
1609  }
1610  break;
1611  case BuiltinType::Char16: {
1612  // char16_t
1613  //ValHolder vh;
1614  //vh.u.c16 = (char16_t) sv_to_ulong_long(fArgVals[i]);
1615  //vh_ary.push_back(vh);
1616  //vp_ary.push_back(&vh_ary.back());
1617  }
1618  break;
1619  case BuiltinType::Char32: {
1620  // char32_t
1621  //ValHolder vh;
1622  //vh.u.c32 = (char32_t) sv_to_ulong_long(fArgVals[i]);
1623  //vh_ary.push_back(vh);
1624  //vp_ary.push_back(&vh_ary.back());
1625  }
1626  break;
1627  case BuiltinType::UShort: {
1628  // unsigned short
1629  ValHolder vh;
1630  vh.u.us = (unsigned short) 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::UInt: {
1636  // unsigned int
1637  ValHolder vh;
1638  vh.u.ui = (unsigned int) 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::ULong: {
1644  // unsigned long
1645  ValHolder vh;
1646  vh.u.ul = (unsigned long) 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::ULongLong: {
1652  // unsigned long long
1653  ValHolder vh;
1654  vh.u.ull = (unsigned long long) 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::UInt128: {
1660  // __uint128_t
1661  }
1662  break;
1663  //
1664  // Signed Types
1665  //
1666  //
1667  // Signed Types
1668  //
1669  case BuiltinType::Char_S: {
1670  // char on targets where it is signed
1671  ValHolder vh;
1672  vh.u.c = (char) sv_to_long_long(fArgVals[i]);
1673  vh_ary.push_back(vh);
1674  vp_ary.push_back(&vh_ary.back());
1675  }
1676  break;
1677  case BuiltinType::SChar: {
1678  // signed char
1679  ValHolder vh;
1680  vh.u.sc = (signed char) sv_to_long_long(fArgVals[i]);
1681  vh_ary.push_back(vh);
1682  vp_ary.push_back(&vh_ary.back());
1683  }
1684  break;
1685  case BuiltinType::WChar_S: {
1686  // wchar_t on targets where it is signed.
1687  // The standard doesn't allow to specify signednedd of wchar_t
1688  // thus this maps simply to wchar_t.
1689  ValHolder vh;
1690  vh.u.wc = (wchar_t) sv_to_long_long(fArgVals[i]);
1691  vh_ary.push_back(vh);
1692  vp_ary.push_back(&vh_ary.back());
1693  }
1694  break;
1695  case BuiltinType::Short: {
1696  // short
1697  ValHolder vh;
1698  vh.u.s = (short) sv_to_long_long(fArgVals[i]);
1699  vh_ary.push_back(vh);
1700  vp_ary.push_back(&vh_ary.back());
1701  }
1702  break;
1703  case BuiltinType::Int: {
1704  // int
1705  ValHolder vh;
1706  vh.u.i = (int) sv_to_long_long(fArgVals[i]);
1707  vh_ary.push_back(vh);
1708  vp_ary.push_back(&vh_ary.back());
1709  }
1710  break;
1711  case BuiltinType::Long: {
1712  // long
1713  ValHolder vh;
1714  vh.u.l = (long) 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::LongLong: {
1720  // long long
1721  ValHolder vh;
1722  vh.u.ll = (long long) 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::Int128: {
1728  // __int128_t
1729  ::Error("TClingCallFunc::exec(void*)",
1730  "Invalid type 'Int128'!");
1731  return;
1732  }
1733  break;
1734  case BuiltinType::Half: {
1735  // half in OpenCL, __fp16 in ARM NEON
1736  ::Error("TClingCallFunc::exec(void*)",
1737  "Invalid type 'Half'!");
1738  return;
1739  }
1740  break;
1741  case BuiltinType::Float: {
1742  // float
1743  ValHolder vh;
1744  vh.u.flt = sv_to<float>(fArgVals[i]);
1745  vh_ary.push_back(vh);
1746  vp_ary.push_back(&vh_ary.back());
1747  }
1748  break;
1749  case BuiltinType::Double: {
1750  // double
1751  ValHolder vh;
1752  vh.u.dbl = sv_to<double>(fArgVals[i]);
1753  vh_ary.push_back(vh);
1754  vp_ary.push_back(&vh_ary.back());
1755  }
1756  break;
1757  case BuiltinType::LongDouble: {
1758  // long double
1759  ValHolder vh;
1760  vh.u.ldbl = sv_to<long double>(fArgVals[i]);
1761  vh_ary.push_back(vh);
1762  vp_ary.push_back(&vh_ary.back());
1763  }
1764  break;
1765  //
1766  // Language-Specific Types
1767  //
1768  case BuiltinType::NullPtr: {
1769  // C++11 nullptr
1770  ValHolder vh;
1771  vh.u.vp = fArgVals[i].getPtr();
1772  vh_ary.push_back(vh);
1773  vp_ary.push_back(&vh_ary.back());
1774  }
1775  break;
1776  default: {
1777  // There should be no others. This is here in case
1778  // this changes in the future.
1779  ::Error("TClingCallFunc::exec(void*)",
1780  "Unhandled builtin type!");
1781  QT->dump();
1782  return;
1783  }
1784  break;
1785  }
1786  } else if (QT->isReferenceType()) {
1787  // the argument is already a pointer value (point to the same thing
1788  // as the reference.
1789  vp_ary.push_back((void *) sv_to_ulong_long(fArgVals[i]));
1790  } else if (QT->isPointerType() || QT->isArrayType()) {
1791  ValHolder vh;
1792  vh.u.vp = (void *) sv_to_ulong_long(fArgVals[i]);
1793  vh_ary.push_back(vh);
1794  vp_ary.push_back(&vh_ary.back());
1795  } else if (QT->isRecordType()) {
1796  // the argument is already a pointer value (pointing to object passed
1797  // by value).
1798  vp_ary.push_back((void *) sv_to_ulong_long(fArgVals[i]));
1799  } else if (const EnumType *ET =
1800  dyn_cast<EnumType>(&*QT)) {
1801  // Note: We may need to worry about the underlying type
1802  // of the enum here.
1803  (void) ET;
1804  ValHolder vh;
1805  vh.u.i = (int) sv_to_long_long(fArgVals[i]);
1806  vh_ary.push_back(vh);
1807  vp_ary.push_back(&vh_ary.back());
1808  } else if (QT->isMemberPointerType()) {
1809  ValHolder vh;
1810  vh.u.vp = (void *) sv_to_ulong_long(fArgVals[i]);
1811  vh_ary.push_back(vh);
1812  vp_ary.push_back(&vh_ary.back());
1813  } else {
1814  ::Error("TClingCallFunc::exec(void*)",
1815  "Invalid type (unrecognized)!");
1816  QT->dump();
1817  return;
1818  }
1819  }
1820  } // End of scope holding the lock
1821  (*fWrapper)(address, (int)num_args, (void **)vp_ary.data(), ret);
1822 }
1823 
1824 template <typename T>
1825 void TClingCallFunc::execWithLL(void *address, cling::Value *val)
1826 {
1827  T ret; // leave uninit for valgrind's sake!
1828  exec(address, &ret);
1829  val->getLL() = ret;
1830 }
1831 
1832 template <typename T>
1834 {
1835  T ret; // leave uninit for valgrind's sake!
1836  exec(address, &ret);
1837  val->getULL() = ret;
1838 }
1839 
1840 // Handle integral types.
1841 template <class T>
1843 {
1844  ret = cling::Value::Create<T>(QT.getAsOpaquePtr(), *fInterp);
1845  static_assert(std::is_integral<T>::value, "Must be called with integral T");
1846  if (std::is_signed<T>::value)
1847  return [this](void* address, cling::Value& ret) { execWithLL<T>(address, &ret); };
1848  else
1849  return [this](void* address, cling::Value& ret) { execWithULL<T>(address, &ret); };
1850 }
1851 
1852 // Handle builtin types.
1854 TClingCallFunc::InitRetAndExecBuiltin(QualType QT, const clang::BuiltinType *BT, cling::Value &ret) {
1855  switch (BT->getKind()) {
1856  case BuiltinType::Void: {
1857  ret = cling::Value::Create<void>(QT.getAsOpaquePtr(), *fInterp);
1858  return [this](void* address, cling::Value& ret) { exec(address, 0); };
1859  break;
1860  }
1861 
1862  //
1863  // Unsigned Types
1864  //
1865  case BuiltinType::Bool:
1866  return InitRetAndExecIntegral<bool>(QT, ret);
1867  break;
1868  case BuiltinType::Char_U: // char on targets where it is unsigned
1869  case BuiltinType::UChar:
1870  return InitRetAndExecIntegral<char>(QT, ret);
1871  break;
1872  case BuiltinType::WChar_U:
1873  return InitRetAndExecIntegral<wchar_t>(QT, ret);
1874  break;
1875  case BuiltinType::Char16:
1876  ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1877  "Invalid type 'char16_t'!");
1878  return {};
1879  break;
1880  case BuiltinType::Char32:
1881  ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1882  "Invalid type 'char32_t'!");
1883  return {};
1884  break;
1885  case BuiltinType::UShort:
1886  return InitRetAndExecIntegral<unsigned short>(QT, ret);
1887  break;
1888  case BuiltinType::UInt:
1889  return InitRetAndExecIntegral<unsigned int>(QT, ret);
1890  break;
1891  case BuiltinType::ULong:
1892  return InitRetAndExecIntegral<unsigned long>(QT, ret);
1893  break;
1894  case BuiltinType::ULongLong:
1895  return InitRetAndExecIntegral<unsigned long long>(QT, ret);
1896  break;
1897  case BuiltinType::UInt128: {
1898  ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1899  "Invalid type '__uint128_t'!");
1900  return {};
1901  }
1902  break;
1903 
1904  //
1905  // Signed Types
1906  //
1907  case BuiltinType::Char_S: // char on targets where it is signed
1908  case BuiltinType::SChar:
1909  return InitRetAndExecIntegral<signed char>(QT, ret);
1910  break;
1911  case BuiltinType::WChar_S:
1912  // wchar_t on targets where it is signed.
1913  // The standard doesn't allow to specify signednedd of wchar_t
1914  // thus this maps simply to wchar_t.
1915  return InitRetAndExecIntegral<wchar_t>(QT, ret);
1916  break;
1917  case BuiltinType::Short:
1918  return InitRetAndExecIntegral<short>(QT, ret);
1919  break;
1920  case BuiltinType::Int:
1921  return InitRetAndExecIntegral<int>(QT, ret);
1922  break;
1923  case BuiltinType::Long:
1924  return InitRetAndExecIntegral<long>(QT, ret);
1925  break;
1926  case BuiltinType::LongLong:
1927  return InitRetAndExecIntegral<long long>(QT, ret);
1928  break;
1929  case BuiltinType::Int128:
1930  ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1931  "Invalid type '__int128_t'!");
1932  return {};
1933  break;
1934  case BuiltinType::Half:
1935  // half in OpenCL, __fp16 in ARM NEON
1936  ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1937  "Invalid type 'Half'!");
1938  return {};
1939  break;
1940  case BuiltinType::Float: {
1941  ret = cling::Value::Create<float>(QT.getAsOpaquePtr(), *fInterp);
1942  return [this](void* address, cling::Value& ret) { exec(address, &ret.getFloat()); };
1943  break;
1944  }
1945  case BuiltinType::Double: {
1946  ret = cling::Value::Create<double>(QT.getAsOpaquePtr(), *fInterp);
1947  return [this](void* address, cling::Value& ret) { exec(address, &ret.getDouble()); };
1948  break;
1949  }
1950  case BuiltinType::LongDouble: {
1951  ret = cling::Value::Create<long double>(QT.getAsOpaquePtr(), *fInterp);
1952  return [this](void* address, cling::Value& ret) { exec(address, &ret.getLongDouble()); };
1953  break;
1954  }
1955  //
1956  // Language-Specific Types
1957  //
1958  case BuiltinType::NullPtr:
1959  // C++11 nullptr
1960  ::Error("TClingCallFunc::InitRetAndExecBuiltin",
1961  "Invalid type 'nullptr'!");
1962  return {};
1963  break;
1964  default:
1965  break;
1966  }
1967  return {};
1968 }
1969 
1970 
1973  if (QT->isReferenceType()) {
1974  ret = cling::Value(QT, *fInterp);
1975  return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
1976  } else if (QT->isMemberPointerType()) {
1977  const MemberPointerType *MPT = QT->getAs<MemberPointerType>();
1978  if (MPT->isMemberDataPointer()) {
1979  // A member data pointer is a actually a struct with one
1980  // member of ptrdiff_t, the offset from the base of the object
1981  // storage to the storage for the designated data member.
1982  // But that's not relevant: we use it as a non-builtin, allocated
1983  // type.
1984  ret = cling::Value(QT, *fInterp);
1985  return [this](void* address, cling::Value& ret) { exec(address, ret.getPtr()); };
1986  }
1987  // We are a function member pointer.
1988  ret = cling::Value(QT, *fInterp);
1989  return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
1990  } else if (QT->isPointerType() || QT->isArrayType()) {
1991  // Note: ArrayType is an illegal function return value type.
1992  ret = cling::Value::Create<void*>(QT.getAsOpaquePtr(), *fInterp);
1993  return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
1994  } else if (QT->isRecordType()) {
1995  ret = cling::Value(QT, *fInterp);
1996  return [this](void* address, cling::Value& ret) { exec(address, ret.getPtr()); };
1997  } else if (const EnumType *ET = dyn_cast<EnumType>(&*QT)) {
1998  // Note: We may need to worry about the underlying type
1999  // of the enum here.
2000  (void) ET;
2001  ret = cling::Value(QT, *fInterp);
2002  return [this](void* address, cling::Value& ret) { execWithLL<int>(address, &ret); };
2003  } else if (const BuiltinType *BT = dyn_cast<BuiltinType>(&*QT)) {
2004  return InitRetAndExecBuiltin(QT, BT, ret);
2005  }
2006  ::Error("TClingCallFunc::exec_with_valref_return",
2007  "Unrecognized return type!");
2008  QT->dump();
2009  return {};
2010 }
2011 
2013 TClingCallFunc::InitRetAndExec(const clang::FunctionDecl *FD, cling::Value &ret) {
2014  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
2015  ASTContext &Context = FD->getASTContext();
2016  const TypeDecl *TD = dyn_cast<TypeDecl>(CD->getDeclContext());
2017  QualType ClassTy(TD->getTypeForDecl(), 0);
2018  QualType QT = Context.getLValueReferenceType(ClassTy);
2019  ret = cling::Value(QT, *fInterp);
2020  // Store the new()'ed address in getPtr()
2021  return [this](void* address, cling::Value& ret) { exec(address, &ret.getPtr()); };
2022  } else {
2023  QualType QT = FD->getReturnType().getCanonicalType();
2024  return InitRetAndExecNoCtor(QT, ret);
2025  }
2026 }
2027 
2029 {
2030  if (!ret) {
2031  exec(address, 0);
2032  return;
2033  }
2034  std::function<void(void*, cling::Value&)> execFunc;
2035 
2036  /* Release lock during user function execution*/
2037  {
2039  execFunc = InitRetAndExec(GetDecl(), *ret);
2040  }
2041 
2042  if (execFunc)
2043  execFunc(address, *ret);
2044  return;
2045 }
2046 
2047 void TClingCallFunc::EvaluateArgList(const string &ArgList)
2048 {
2050 
2051  SmallVector<Expr *, 4> exprs;
2052  fInterp->getLookupHelper().findArgList(ArgList, exprs,
2053  gDebug > 5 ? cling::LookupHelper::WithDiagnostics
2054  : cling::LookupHelper::NoDiagnostics);
2055  for (SmallVectorImpl<Expr *>::const_iterator I = exprs.begin(),
2056  E = exprs.end(); I != E; ++I) {
2057  cling::Value val;
2058  EvaluateExpr(*fInterp, *I, val);
2059  if (!val.isValid()) {
2060  // Bad expression, all done.
2061  ::Error("TClingCallFunc::EvaluateArgList",
2062  "Bad expression in parameter %d of '%s'!",
2063  (int)(I - exprs.begin()),
2064  ArgList.c_str());
2065  return;
2066  }
2067  fArgVals.push_back(val);
2068  }
2069 }
2070 
2071 void TClingCallFunc::Exec(void *address, TInterpreterValue *interpVal/*=0*/)
2072 {
2073  IFacePtr();
2074  if (!fWrapper) {
2075  ::Error("TClingCallFunc::Exec(address, interpVal)",
2076  "Called with no wrapper, not implemented!");
2077  return;
2078  }
2079  if (!interpVal) {
2080  exec(address, 0);
2081  return;
2082  }
2083  cling::Value *val = reinterpret_cast<cling::Value *>(interpVal->GetValAddr());
2084  exec_with_valref_return(address, val);
2085 }
2086 
2087 template <typename T>
2088 T TClingCallFunc::ExecT(void *address)
2089 {
2090  IFacePtr();
2091  if (!fWrapper) {
2092  ::Error("TClingCallFunc::ExecT",
2093  "Called with no wrapper, not implemented!");
2094  return 0;
2095  }
2096  cling::Value ret;
2097  exec_with_valref_return(address, &ret);
2098  if (!ret.isValid()) {
2099  // Sometimes we are called on a function returning void!
2100  return 0;
2101  }
2102 
2103  if (fReturnIsRecordType)
2104  ((TCling *)gCling)->RegisterTemporary(ret);
2105  return sv_to<T>(ret);
2106 }
2107 
2109 {
2110  return ExecT<long>(address);
2111 }
2112 
2113 long long TClingCallFunc::ExecInt64(void *address)
2114 {
2115  return ExecT<long long>(address);
2116 }
2117 
2118 double TClingCallFunc::ExecDouble(void *address)
2119 {
2120  return ExecT<double>(address);
2121 }
2122 
2123 void TClingCallFunc::ExecWithArgsAndReturn(void *address, const void *args[] /*= 0*/,
2124  int nargs /*= 0*/, void *ret/*= 0*/)
2125 {
2126  IFacePtr();
2127  if (!fWrapper) {
2128  ::Error("TClingCallFunc::ExecWithArgsAndReturn(address, args, ret)",
2129  "Called with no wrapper, not implemented!");
2130  return;
2131  }
2132  (*fWrapper)(address, nargs, const_cast<void **>(args), ret);
2133 }
2134 
2135 void TClingCallFunc::ExecWithReturn(void *address, void *ret/*= 0*/)
2136 {
2137  IFacePtr();
2138  if (!fWrapper) {
2139  ::Error("TClingCallFunc::ExecWithReturn(address, ret)",
2140  "Called with no wrapper, not implemented!");
2141  return;
2142  }
2143  exec(address, ret);
2144 }
2145 
2148  const std::string &type_name,
2149  void *address /*=0*/, unsigned long nary /*= 0UL*/)
2150 {
2151  if (!info->IsValid()) {
2152  ::Error("TClingCallFunc::ExecDefaultConstructor", "Invalid class info!");
2153  return nullptr;
2154  }
2155  tcling_callfunc_ctor_Wrapper_t wrapper = nullptr;
2156  {
2158  auto D = info->GetDecl();
2159  //if (!info->HasDefaultConstructor()) {
2160  // // FIXME: We might have a ROOT ioctor, we might
2161  // // have to check for that here.
2162  // ::Error("TClingCallFunc::ExecDefaultConstructor",
2163  // "Class has no default constructor: %s",
2164  // info->Name());
2165  // return 0;
2166  //}
2167  auto I = gCtorWrapperStore.find(D);
2168  if (I != gCtorWrapperStore.end()) {
2169  wrapper = (tcling_callfunc_ctor_Wrapper_t) I->second;
2170  } else {
2171  wrapper = make_ctor_wrapper(info, kind, type_name);
2172  }
2173  }
2174  if (!wrapper) {
2175  ::Error("TClingCallFunc::ExecDefaultConstructor",
2176  "Called with no wrapper, not implemented!");
2177  return nullptr;
2178  }
2179  void *obj = 0;
2180  (*wrapper)(&obj, address, nary);
2181  return obj;
2182 }
2183 
2184 void TClingCallFunc::ExecDestructor(const TClingClassInfo *info, void *address /*=0*/,
2185  unsigned long nary /*= 0UL*/, bool withFree /*= true*/)
2186 {
2187  if (!info->IsValid()) {
2188  ::Error("TClingCallFunc::ExecDestructor", "Invalid class info!");
2189  return;
2190  }
2191 
2192  tcling_callfunc_dtor_Wrapper_t wrapper = 0;
2193  {
2195  const Decl *D = info->GetDecl();
2196  map<const Decl *, void *>::iterator I = gDtorWrapperStore.find(D);
2197  if (I != gDtorWrapperStore.end()) {
2198  wrapper = (tcling_callfunc_dtor_Wrapper_t) I->second;
2199  } else {
2200  wrapper = make_dtor_wrapper(info);
2201  }
2202  }
2203  if (!wrapper) {
2204  ::Error("TClingCallFunc::ExecDestructor",
2205  "Called with no wrapper, not implemented!");
2206  return;
2207  }
2208  (*wrapper)(address, nary, withFree);
2209 }
2210 
2213 {
2214  return new TClingMethodInfo(*fMethod);
2215 }
2216 
2218 {
2219  fMethod.reset();
2220  fWrapper = 0;
2221  fDecl = nullptr;
2222  fMinRequiredArguments = -1;
2223  ResetArg();
2224 }
2225 
2227 {
2228  Init();
2229  fMethod = std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(minfo));
2230 }
2231 
2232 void TClingCallFunc::Init(std::unique_ptr<TClingMethodInfo> minfo)
2233 {
2234  Init();
2235  fMethod = std::move(minfo);
2236 }
2237 
2239 {
2240  if (!IsValid()) {
2241  return 0;
2242  }
2243  if (!fWrapper) {
2244  const FunctionDecl *decl = GetDecl();
2245 
2247  map<const FunctionDecl *, void *>::iterator I = gWrapperStore.find(decl);
2248  if (I != gWrapperStore.end()) {
2249  fWrapper = (tcling_callfunc_Wrapper_t) I->second;
2250  } else {
2251  fWrapper = make_wrapper();
2252  }
2253  }
2254  return (void *)fWrapper;
2255 }
2256 
2258 {
2259  if (!fMethod) {
2260  return false;
2261  }
2262  return fMethod->IsValid();
2263 }
2264 
2266 {
2267  if (!IsValid()) {
2268  ::Error("TClingCallFunc::IFacePtr(kind)",
2269  "Attempt to get interface while invalid.");
2271  }
2272  if (!fWrapper) {
2273  const FunctionDecl *decl = GetDecl();
2274 
2276  map<const FunctionDecl *, void *>::iterator I = gWrapperStore.find(decl);
2277  if (I != gWrapperStore.end()) {
2278  fWrapper = (tcling_callfunc_Wrapper_t) I->second;
2279  } else {
2280  fWrapper = make_wrapper();
2281  }
2282 
2283  fReturnIsRecordType = decl->getReturnType().getCanonicalType()->isRecordType();
2284  }
2285  return TInterpreter::CallFuncIFacePtr_t(fWrapper);
2286 }
2287 
2288 
2290 {
2291  fArgVals.clear();
2292 }
2293 
2294 void TClingCallFunc::SetArg(unsigned long param)
2295 {
2296  const ASTContext &C = fInterp->getCI()->getASTContext();
2297  fArgVals.push_back(cling::Value(C.UnsignedLongTy, *fInterp));
2298  fArgVals.back().getLL() = param;
2299 }
2300 
2301 void TClingCallFunc::SetArg(long param)
2302 {
2303  const ASTContext &C = fInterp->getCI()->getASTContext();
2304  fArgVals.push_back(cling::Value(C.LongTy, *fInterp));
2305  fArgVals.back().getLL() = param;
2306 }
2307 
2308 void TClingCallFunc::SetArg(float param)
2309 {
2310  const ASTContext &C = fInterp->getCI()->getASTContext();
2311  fArgVals.push_back(cling::Value(C.FloatTy, *fInterp));
2312  fArgVals.back().getFloat() = param;
2313 }
2314 
2315 void TClingCallFunc::SetArg(double param)
2316 {
2317  const ASTContext &C = fInterp->getCI()->getASTContext();
2318  fArgVals.push_back(cling::Value(C.DoubleTy, *fInterp));
2319  fArgVals.back().getDouble() = param;
2320 }
2321 
2322 void TClingCallFunc::SetArg(long long param)
2323 {
2324  const ASTContext &C = fInterp->getCI()->getASTContext();
2325  fArgVals.push_back(cling::Value(C.LongLongTy, *fInterp));
2326  fArgVals.back().getLL() = param;
2327 }
2328 
2329 void TClingCallFunc::SetArg(unsigned long long param)
2330 {
2331  const ASTContext &C = fInterp->getCI()->getASTContext();
2332  fArgVals.push_back(cling::Value(C.UnsignedLongLongTy, *fInterp));
2333  fArgVals.back().getULL() = param;
2334 }
2335 
2336 void TClingCallFunc::SetArgArray(long *paramArr, int nparam)
2337 {
2338  ResetArg();
2339  for (int i = 0; i < nparam; ++i) {
2340  SetArg(paramArr[i]);
2341  }
2342 }
2343 
2344 void TClingCallFunc::SetArgs(const char *params)
2345 {
2346  ResetArg();
2347  EvaluateArgList(params);
2348 }
2349 
2350 void TClingCallFunc::SetFunc(const TClingClassInfo *info, const char *method, const char *arglist,
2351  long *poffset)
2352 {
2353  SetFunc(info, method, arglist, false, poffset);
2354 }
2355 
2356 void TClingCallFunc::SetFunc(const TClingClassInfo *info, const char *method, const char *arglist,
2357  bool objectIsConst, long *poffset)
2358 {
2359  Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2360  if (poffset) {
2361  *poffset = 0L;
2362  }
2363  ResetArg();
2364  if (!info->IsValid()) {
2365  ::Error("TClingCallFunc::SetFunc", "Class info is invalid!");
2366  return;
2367  }
2368  if (!strcmp(arglist, ")")) {
2369  // CINT accepted a single right paren as meaning no arguments.
2370  arglist = "";
2371  }
2372  *fMethod = info->GetMethodWithArgs(method, arglist, objectIsConst, poffset);
2373  if (!fMethod->IsValid()) {
2374  //::Error("TClingCallFunc::SetFunc", "Could not find method %s(%s)", method,
2375  // arglist);
2376  return;
2377  }
2378  // FIXME: The arglist was already parsed by the lookup, we should
2379  // enhance the lookup to return the resulting expression
2380  // list so we do not need to parse it again here.
2381  EvaluateArgList(arglist);
2382 }
2383 
2385 {
2386  Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(*info)));
2387  ResetArg();
2388  if (!fMethod->IsValid()) {
2389  return;
2390  }
2391 }
2392 
2393 void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2394  const char *proto, long *poffset,
2395  EFunctionMatchMode mode/*=kConversionMatch*/)
2396 {
2397  SetFuncProto(info, method, proto, false, poffset, mode);
2398 }
2399 
2400 void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2401  const char *proto, bool objectIsConst, long *poffset,
2402  EFunctionMatchMode mode/*=kConversionMatch*/)
2403 {
2404  Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2405  if (poffset) {
2406  *poffset = 0L;
2407  }
2408  ResetArg();
2409  if (!info->IsValid()) {
2410  ::Error("TClingCallFunc::SetFuncProto", "Class info is invalid!");
2411  return;
2412  }
2413  *fMethod = info->GetMethod(method, proto, objectIsConst, poffset, mode);
2414  if (!fMethod->IsValid()) {
2415  //::Error("TClingCallFunc::SetFuncProto", "Could not find method %s(%s)",
2416  // method, proto);
2417  return;
2418  }
2419 }
2420 
2421 void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2422  const llvm::SmallVectorImpl<clang::QualType> &proto, long *poffset,
2423  EFunctionMatchMode mode/*=kConversionMatch*/)
2424 {
2425  SetFuncProto(info, method, proto, false, poffset, mode);
2426 }
2427 
2428 void TClingCallFunc::SetFuncProto(const TClingClassInfo *info, const char *method,
2429  const llvm::SmallVectorImpl<clang::QualType> &proto,
2430  bool objectIsConst, long *poffset,
2431  EFunctionMatchMode mode/*=kConversionMatch*/)
2432 {
2433  Init(std::unique_ptr<TClingMethodInfo>(new TClingMethodInfo(fInterp)));
2434  if (poffset) {
2435  *poffset = 0L;
2436  }
2437  ResetArg();
2438  if (!info->IsValid()) {
2439  ::Error("TClingCallFunc::SetFuncProto", "Class info is invalid!");
2440  return;
2441  }
2442  *fMethod = info->GetMethod(method, proto, objectIsConst, poffset, mode);
2443  if (!fMethod->IsValid()) {
2444  //::Error("TClingCallFunc::SetFuncProto", "Could not find method %s(%s)",
2445  // method, proto);
2446  return;
2447  }
2448 }
2449 
ExecWithRetFunc_t InitRetAndExecBuiltin(clang::QualType QT, const clang::BuiltinType *BT, cling::Value &ret)
static constexpr double us
Definition: TString.h:845
void * compile_wrapper(const std::string &wrapper_name, const std::string &wrapper, bool withAccessControl=true)
Returns the available number of logical cores.
Definition: StringConv.hxx:21
const char * Int
double ExecDouble(void *address)
double T(double x)
Definition: ChebyshevPol.h:34
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)
R__EXTERN TVirtualMutex * gInterpreterMutex
Definition: TInterpreter.h:41
static map< const FunctionDecl *, void * > gWrapperStore
TClingMethodInfo GetMethod(const char *fname) const
void SetFunc(const TClingClassInfo *info, const char *method, const char *arglist, long *poffset)
void SetArgArray(long *argArr, int narg)
tcling_callfunc_dtor_Wrapper_t make_dtor_wrapper(const TClingClassInfo *info)
ExecWithRetFunc_t InitRetAndExecNoCtor(clang::QualType QT, cling::Value &ret)
Emulation of the CINT MethodInfo class.
void SetArg(long arg)
#define N
static map< const Decl *, void * > gDtorWrapperStore
const char * Long
Definition: Pattern.h:7
ExecWithRetFunc_t InitRetAndExecIntegral(clang::QualType QT, cling::Value &ret)
virtual bool IsValid() const
static map< const Decl *, void * > gCtorWrapperStore
STL namespace.
const char * UShort
std::function< void(void *address, cling::Value &ret)> ExecWithRetFunc_t
const char * UInt
#define R__LOCKGUARD_CLING(mutex)
Definition: TInterpreter.h:48
void Exec(void *address, TInterpreterValue *interpVal=0)
TInterpreter::CallFuncIFacePtr_t IFacePtr()
static unsigned long long gWrapperSerial
void SetArgs(const char *args)
void Init(TClassEdit::TInterpreterLookupHelper *helper)
Definition: TClassEdit.cxx:154
void(* tcling_callfunc_ctor_Wrapper_t)(void **, void *, unsigned long)
T ExecT(void *address)
void(* tcling_callfunc_dtor_Wrapper_t)(void *, unsigned long, int)
EFunctionMatchMode
Definition: TDictionary.h:155
static constexpr double s
This class defines an interface to the cling C++ interpreter.
Definition: TCling.h:99
R__EXTERN Int_t gDebug
Definition: RtypesCore.h:117
void Error(const char *location, const char *msgfmt,...)
void * InterfaceMethod()
const char * UChar
const char * Float
void execWithULL(void *address, cling::Value *val)
void * ExecDefaultConstructor(const TClingClassInfo *info, ROOT::TMetaUtils::EIOCtorCategory kind, const std::string &type_name, void *address=nullptr, unsigned long nary=0UL)
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, etc.) and adding default template argument for all types except the STL collections where we remove the default template argument if any.
tcling_callfunc_ctor_Wrapper_t make_ctor_wrapper(const TClingClassInfo *, ROOT::TMetaUtils::EIOCtorCategory, const std::string &)
RooArgSet S(const RooAbsArg &v1)
#define F(x, y, z)
static const string kIndentString(" ")
static double C[]
TClingMethodInfo * FactoryMethod() const
void SetFuncProto(const TClingClassInfo *info, const char *method, const char *proto, long *poffset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
void ExecWithReturn(void *address, void *ret=nullptr)
void EvaluateArgList(const std::string &ArgList)
void execWithLL(void *address, cling::Value *val)
const char * ULong
void exec_with_valref_return(void *address, cling::Value *ret)
const char * Double
void make_narg_ctor(const unsigned N, std::ostringstream &typedefbuf, std::ostringstream &callbuf, const std::string &class_name, int indent_level)
static void indent(ostringstream &buf, int indent_level)
static void EvaluateExpr(cling::Interpreter &interp, const Expr *E, cling::Value &V)
constexpr Double_t E()
Base of natural log: .
Definition: TMath.h:97
int get_wrapper_code(std::string &wrapper_name, std::string &wrapper)
long Long_t
Definition: RtypesCore.h:52
tcling_callfunc_Wrapper_t make_wrapper()
size_t CalculateMinRequiredArguments()
virtual const clang::Decl * GetDecl() const
virtual const void * GetValAddr() const =0
static constexpr double L
void make_narg_call_with_return(const unsigned N, const std::string &class_name, std::ostringstream &buf, int indent_level)
Emulation of the CINT ClassInfo class.
static constexpr double nm
const char * Bool
void(* tcling_callfunc_Wrapper_t)(void *, int, void **, void *)
typedef void((*Func_t)())
auto * l
Definition: textangle.C:4
bool IsValid() const
void make_narg_ctor_with_return(const unsigned N, const std::string &class_name, std::ostringstream &buf, int indent_level)
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)
you should not use this method at all Int_t Int_t Double_t Double_t Double_t Int_t Double_t Double_t Double_t Double_t b
Definition: TRolke.cxx:630
long ExecInt(void *address)
const char * proto
Definition: civetweb.c:16604
#define c(i)
Definition: RSha256.hxx:101
ExecWithRetFunc_t InitRetAndExec(const clang::FunctionDecl *FD, cling::Value &ret)
void ExecDestructor(const TClingClassInfo *info, void *address=nullptr, unsigned long nary=0UL, bool withFree=true)
R__EXTERN TInterpreter * gCling
Definition: TInterpreter.h:557
#define I(x, y, z)
void exec(void *address, void *ret)
char name[80]
Definition: TGX11.cxx:109
void ExecWithArgsAndReturn(void *address, const void *args[]=0, int nargs=0, void *ret=0)
const char * Value
Definition: TXMLSetup.cxx:73
TClingMethodInfo GetMethodWithArgs(const char *fname, const char *arglist, long *poffset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch, EInheritanceMode imode=kWithInheritance) const
const char * Short
long long ExecInt64(void *address)