clang  6.0.0svn
CGVTables.cpp
Go to the documentation of this file.
1 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with C++ code generation of virtual tables.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGCXXABI.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
18 #include "clang/AST/RecordLayout.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Transforms/Utils/Cloning.h"
25 #include <algorithm>
26 #include <cstdio>
27 
28 using namespace clang;
29 using namespace CodeGen;
30 
32  : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
33 
35  const ThunkInfo &Thunk) {
36  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
37 
38  // Compute the mangled name.
39  SmallString<256> Name;
40  llvm::raw_svector_ostream Out(Name);
41  if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
42  getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
43  Thunk.This, Out);
44  else
45  getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
46 
47  llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
48  return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
49  /*DontDefer=*/true, /*IsThunk=*/true);
50 }
51 
52 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
53  const ThunkInfo &Thunk, llvm::Function *Fn) {
55 }
56 
57 static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
58  llvm::Function *ThunkFn, bool ForVTable,
59  GlobalDecl GD) {
60  CGM.setFunctionLinkage(GD, ThunkFn);
61  CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
62  !Thunk.Return.isEmpty());
63 
64  // Set the right visibility.
65  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
66  setThunkVisibility(CGM, MD, Thunk, ThunkFn);
67 
68  if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
69  ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
70 }
71 
72 #ifndef NDEBUG
73 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
74  const ABIArgInfo &infoR, CanQualType typeR) {
75  return (infoL.getKind() == infoR.getKind() &&
76  (typeL == typeR ||
77  (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
78  (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
79 }
80 #endif
81 
83  QualType ResultType, RValue RV,
84  const ThunkInfo &Thunk) {
85  // Emit the return adjustment.
86  bool NullCheckValue = !ResultType->isReferenceType();
87 
88  llvm::BasicBlock *AdjustNull = nullptr;
89  llvm::BasicBlock *AdjustNotNull = nullptr;
90  llvm::BasicBlock *AdjustEnd = nullptr;
91 
92  llvm::Value *ReturnValue = RV.getScalarVal();
93 
94  if (NullCheckValue) {
95  AdjustNull = CGF.createBasicBlock("adjust.null");
96  AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
97  AdjustEnd = CGF.createBasicBlock("adjust.end");
98 
99  llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
100  CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
101  CGF.EmitBlock(AdjustNotNull);
102  }
103 
104  auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
105  auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
106  ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
107  Address(ReturnValue, ClassAlign),
108  Thunk.Return);
109 
110  if (NullCheckValue) {
111  CGF.Builder.CreateBr(AdjustEnd);
112  CGF.EmitBlock(AdjustNull);
113  CGF.Builder.CreateBr(AdjustEnd);
114  CGF.EmitBlock(AdjustEnd);
115 
116  llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
117  PHI->addIncoming(ReturnValue, AdjustNotNull);
118  PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
119  AdjustNull);
120  ReturnValue = PHI;
121  }
122 
123  return RValue::get(ReturnValue);
124 }
125 
126 /// This function clones a function's DISubprogram node and enters it into
127 /// a value map with the intent that the map can be utilized by the cloner
128 /// to short-circuit Metadata node mapping.
129 /// Furthermore, the function resolves any DILocalVariable nodes referenced
130 /// by dbg.value intrinsics so they can be properly mapped during cloning.
131 static void resolveTopLevelMetadata(llvm::Function *Fn,
132  llvm::ValueToValueMapTy &VMap) {
133  // Clone the DISubprogram node and put it into the Value map.
134  auto *DIS = Fn->getSubprogram();
135  if (!DIS)
136  return;
137  auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
138  VMap.MD()[DIS].reset(NewDIS);
139 
140  // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
141  // they are referencing.
142  for (auto &BB : Fn->getBasicBlockList()) {
143  for (auto &I : BB) {
144  if (auto *DII = dyn_cast<llvm::DbgInfoIntrinsic>(&I)) {
145  auto *DILocal = DII->getVariable();
146  if (!DILocal->isResolved())
147  DILocal->resolve();
148  }
149  }
150  }
151 }
152 
153 // This function does roughly the same thing as GenerateThunk, but in a
154 // very different way, so that va_start and va_end work correctly.
155 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
156 // a function, and that there is an alloca built in the entry block
157 // for all accesses to "this".
158 // FIXME: This function assumes there is only one "ret" statement per function.
159 // FIXME: Cloning isn't correct in the presence of indirect goto!
160 // FIXME: This implementation of thunks bloats codesize by duplicating the
161 // function definition. There are alternatives:
162 // 1. Add some sort of stub support to LLVM for cases where we can
163 // do a this adjustment, then a sibcall.
164 // 2. We could transform the definition to take a va_list instead of an
165 // actual variable argument list, then have the thunks (including a
166 // no-op thunk for the regular definition) call va_start/va_end.
167 // There's a bit of per-call overhead for this solution, but it's
168 // better for codesize if the definition is long.
169 llvm::Function *
171  const CGFunctionInfo &FnInfo,
172  GlobalDecl GD, const ThunkInfo &Thunk) {
173  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
174  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
175  QualType ResultType = FPT->getReturnType();
176 
177  // Get the original function
178  assert(FnInfo.isVariadic());
179  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
180  llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
181  llvm::Function *BaseFn = cast<llvm::Function>(Callee);
182 
183  // Clone to thunk.
184  llvm::ValueToValueMapTy VMap;
185 
186  // We are cloning a function while some Metadata nodes are still unresolved.
187  // Ensure that the value mapper does not encounter any of them.
188  resolveTopLevelMetadata(BaseFn, VMap);
189  llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
190  Fn->replaceAllUsesWith(NewFn);
191  NewFn->takeName(Fn);
192  Fn->eraseFromParent();
193  Fn = NewFn;
194 
195  // "Initialize" CGF (minimally).
196  CurFn = Fn;
197 
198  // Get the "this" value
199  llvm::Function::arg_iterator AI = Fn->arg_begin();
200  if (CGM.ReturnTypeUsesSRet(FnInfo))
201  ++AI;
202 
203  // Find the first store of "this", which will be to the alloca associated
204  // with "this".
205  Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
206  llvm::BasicBlock *EntryBB = &Fn->front();
207  llvm::BasicBlock::iterator ThisStore =
208  std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
209  return isa<llvm::StoreInst>(I) &&
210  I.getOperand(0) == ThisPtr.getPointer();
211  });
212  assert(ThisStore != EntryBB->end() &&
213  "Store of this should be in entry block?");
214  // Adjust "this", if necessary.
215  Builder.SetInsertPoint(&*ThisStore);
216  llvm::Value *AdjustedThisPtr =
217  CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
218  ThisStore->setOperand(0, AdjustedThisPtr);
219 
220  if (!Thunk.Return.isEmpty()) {
221  // Fix up the returned value, if necessary.
222  for (llvm::BasicBlock &BB : *Fn) {
223  llvm::Instruction *T = BB.getTerminator();
224  if (isa<llvm::ReturnInst>(T)) {
225  RValue RV = RValue::get(T->getOperand(0));
226  T->eraseFromParent();
227  Builder.SetInsertPoint(&BB);
228  RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
229  Builder.CreateRet(RV.getScalarVal());
230  break;
231  }
232  }
233  }
234 
235  return Fn;
236 }
237 
238 void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
239  const CGFunctionInfo &FnInfo) {
240  assert(!CurGD.getDecl() && "CurGD was already set!");
241  CurGD = GD;
242  CurFuncIsThunk = true;
243 
244  // Build FunctionArgs.
245  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
246  QualType ThisType = MD->getThisType(getContext());
247  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
248  QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
249  ? ThisType
250  : CGM.getCXXABI().hasMostDerivedReturn(GD)
251  ? CGM.getContext().VoidPtrTy
252  : FPT->getReturnType();
253  FunctionArgList FunctionArgs;
254 
255  // Create the implicit 'this' parameter declaration.
256  CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
257 
258  // Add the rest of the parameters.
259  FunctionArgs.append(MD->param_begin(), MD->param_end());
260 
261  if (isa<CXXDestructorDecl>(MD))
262  CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
263 
264  // Start defining the function.
265  auto NL = ApplyDebugLocation::CreateEmpty(*this);
266  StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
267  MD->getLocation());
268  // Create a scope with an artificial location for the body of this function.
269  auto AL = ApplyDebugLocation::CreateArtificial(*this);
270 
271  // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
273  CXXThisValue = CXXABIThisValue;
274  CurCodeDecl = MD;
275  CurFuncDecl = MD;
276 }
277 
279  // Clear these to restore the invariants expected by
280  // StartFunction/FinishFunction.
281  CurCodeDecl = nullptr;
282  CurFuncDecl = nullptr;
283 
284  FinishFunction();
285 }
286 
287 void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Constant *CalleePtr,
288  const ThunkInfo *Thunk) {
289  assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
290  "Please use a new CGF for this thunk");
291  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
292 
293  // Adjust the 'this' pointer if necessary
294  llvm::Value *AdjustedThisPtr =
295  Thunk ? CGM.getCXXABI().performThisAdjustment(
296  *this, LoadCXXThisAddress(), Thunk->This)
297  : LoadCXXThis();
298 
299  if (CurFnInfo->usesInAlloca()) {
300  // We don't handle return adjusting thunks, because they require us to call
301  // the copy constructor. For now, fall through and pretend the return
302  // adjustment was empty so we don't crash.
303  if (Thunk && !Thunk->Return.isEmpty()) {
304  CGM.ErrorUnsupported(
305  MD, "non-trivial argument copy for return-adjusting thunk");
306  }
307  EmitMustTailThunk(MD, AdjustedThisPtr, CalleePtr);
308  return;
309  }
310 
311  // Start building CallArgs.
312  CallArgList CallArgs;
313  QualType ThisType = MD->getThisType(getContext());
314  CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
315 
316  if (isa<CXXDestructorDecl>(MD))
317  CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
318 
319 #ifndef NDEBUG
320  unsigned PrefixArgs = CallArgs.size() - 1;
321 #endif
322  // Add the rest of the arguments.
323  for (const ParmVarDecl *PD : MD->parameters())
324  EmitDelegateCallArg(CallArgs, PD, SourceLocation());
325 
326  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
327 
328 #ifndef NDEBUG
329  const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
330  CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1, MD), PrefixArgs);
331  assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
332  CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
333  CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
334  assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
335  similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
336  CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
337  assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
338  for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
339  assert(similar(CallFnInfo.arg_begin()[i].info,
340  CallFnInfo.arg_begin()[i].type,
341  CurFnInfo->arg_begin()[i].info,
342  CurFnInfo->arg_begin()[i].type));
343 #endif
344 
345  // Determine whether we have a return value slot to use.
346  QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
347  ? ThisType
348  : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
349  ? CGM.getContext().VoidPtrTy
350  : FPT->getReturnType();
351  ReturnValueSlot Slot;
352  if (!ResultType->isVoidType() &&
353  CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
354  !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
355  Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
356 
357  // Now emit our call.
358  llvm::Instruction *CallOrInvoke;
359  CGCallee Callee = CGCallee::forDirect(CalleePtr, MD);
360  RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, &CallOrInvoke);
361 
362  // Consider return adjustment if we have ThunkInfo.
363  if (Thunk && !Thunk->Return.isEmpty())
364  RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
365  else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
366  Call->setTailCallKind(llvm::CallInst::TCK_Tail);
367 
368  // Emit return.
369  if (!ResultType->isVoidType() && Slot.isNull())
370  CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
371 
372  // Disable the final ARC autorelease.
373  AutoreleaseResult = false;
374 
375  FinishThunk();
376 }
377 
379  llvm::Value *AdjustedThisPtr,
380  llvm::Value *CalleePtr) {
381  // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
382  // to translate AST arguments into LLVM IR arguments. For thunks, we know
383  // that the caller prototype more or less matches the callee prototype with
384  // the exception of 'this'.
386  for (llvm::Argument &A : CurFn->args())
387  Args.push_back(&A);
388 
389  // Set the adjusted 'this' pointer.
390  const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
391  if (ThisAI.isDirect()) {
392  const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
393  int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
394  llvm::Type *ThisType = Args[ThisArgNo]->getType();
395  if (ThisType != AdjustedThisPtr->getType())
396  AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
397  Args[ThisArgNo] = AdjustedThisPtr;
398  } else {
399  assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
400  Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
401  llvm::Type *ThisType = ThisAddr.getElementType();
402  if (ThisType != AdjustedThisPtr->getType())
403  AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
404  Builder.CreateStore(AdjustedThisPtr, ThisAddr);
405  }
406 
407  // Emit the musttail call manually. Even if the prologue pushed cleanups, we
408  // don't actually want to run them.
409  llvm::CallInst *Call = Builder.CreateCall(CalleePtr, Args);
410  Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
411 
412  // Apply the standard set of call attributes.
413  unsigned CallingConv;
414  llvm::AttributeList Attrs;
415  CGM.ConstructAttributeList(CalleePtr->getName(), *CurFnInfo, MD, Attrs,
416  CallingConv, /*AttrOnCallSite=*/true);
417  Call->setAttributes(Attrs);
418  Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
419 
420  if (Call->getType()->isVoidTy())
421  Builder.CreateRetVoid();
422  else
423  Builder.CreateRet(Call);
424 
425  // Finish the function to maintain CodeGenFunction invariants.
426  // FIXME: Don't emit unreachable code.
427  EmitBlock(createBasicBlock());
428  FinishFunction();
429 }
430 
431 void CodeGenFunction::generateThunk(llvm::Function *Fn,
432  const CGFunctionInfo &FnInfo,
433  GlobalDecl GD, const ThunkInfo &Thunk) {
434  StartThunk(Fn, GD, FnInfo);
435  // Create a scope with an artificial location for the body of this function.
436  auto AL = ApplyDebugLocation::CreateArtificial(*this);
437 
438  // Get our callee.
439  llvm::Type *Ty =
441  llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
442 
443  // Make the call and return the result.
444  EmitCallAndReturnForThunk(Callee, &Thunk);
445 }
446 
447 void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
448  bool ForVTable) {
449  const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
450 
451  // FIXME: re-use FnInfo in this computation.
452  llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
453  llvm::GlobalValue *Entry;
454 
455  // Strip off a bitcast if we got one back.
456  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
457  assert(CE->getOpcode() == llvm::Instruction::BitCast);
458  Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
459  } else {
460  Entry = cast<llvm::GlobalValue>(C);
461  }
462 
463  // There's already a declaration with the same name, check if it has the same
464  // type or if we need to replace it.
465  if (Entry->getType()->getElementType() !=
467  llvm::GlobalValue *OldThunkFn = Entry;
468 
469  // If the types mismatch then we have to rewrite the definition.
470  assert(OldThunkFn->isDeclaration() &&
471  "Shouldn't replace non-declaration");
472 
473  // Remove the name from the old thunk function and get a new thunk.
474  OldThunkFn->setName(StringRef());
475  Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
476 
477  // If needed, replace the old thunk with a bitcast.
478  if (!OldThunkFn->use_empty()) {
479  llvm::Constant *NewPtrForOldDecl =
480  llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
481  OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
482  }
483 
484  // Remove the old thunk.
485  OldThunkFn->eraseFromParent();
486  }
487 
488  llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
489  bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
490  bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
491 
492  if (!ThunkFn->isDeclaration()) {
493  if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
494  // There is already a thunk emitted for this function, do nothing.
495  return;
496  }
497 
498  setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
499  return;
500  }
501 
503 
504  if (ThunkFn->isVarArg()) {
505  // Varargs thunks are special; we can't just generate a call because
506  // we can't copy the varargs. Our implementation is rather
507  // expensive/sucky at the moment, so don't generate the thunk unless
508  // we have to.
509  // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
510  if (UseAvailableExternallyLinkage)
511  return;
512  ThunkFn =
513  CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
514  } else {
515  // Normal thunk body generation.
516  CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
517  }
518 
519  setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
520 }
521 
522 void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
523  const ThunkInfo &Thunk) {
524  // If the ABI has key functions, only the TU with the key function should emit
525  // the thunk. However, we can allow inlining of thunks if we emit them with
526  // available_externally linkage together with vtables when optimizations are
527  // enabled.
528  if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
529  !CGM.getCodeGenOpts().OptimizationLevel)
530  return;
531 
532  // We can't emit thunks for member functions with incomplete types.
533  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
534  if (!CGM.getTypes().isFuncTypeConvertible(
535  MD->getType()->castAs<FunctionType>()))
536  return;
537 
538  emitThunk(GD, Thunk, /*ForVTable=*/true);
539 }
540 
542 {
543  const CXXMethodDecl *MD =
544  cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
545 
546  // We don't need to generate thunks for the base destructor.
547  if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
548  return;
549 
550  const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
551  VTContext->getThunkInfo(GD);
552 
553  if (!ThunkInfoVector)
554  return;
555 
556  for (const ThunkInfo& Thunk : *ThunkInfoVector)
557  emitThunk(GD, Thunk, /*ForVTable=*/false);
558 }
559 
560 void CodeGenVTables::addVTableComponent(
561  ConstantArrayBuilder &builder, const VTableLayout &layout,
562  unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
563  auto &component = layout.vtable_components()[idx];
564 
565  auto addOffsetConstant = [&](CharUnits offset) {
566  builder.add(llvm::ConstantExpr::getIntToPtr(
567  llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
568  CGM.Int8PtrTy));
569  };
570 
571  switch (component.getKind()) {
573  return addOffsetConstant(component.getVCallOffset());
574 
576  return addOffsetConstant(component.getVBaseOffset());
577 
579  return addOffsetConstant(component.getOffsetToTop());
580 
582  return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
583 
587  GlobalDecl GD;
588 
589  // Get the right global decl.
590  switch (component.getKind()) {
591  default:
592  llvm_unreachable("Unexpected vtable component kind");
594  GD = component.getFunctionDecl();
595  break;
597  GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
598  break;
600  GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
601  break;
602  }
603 
604  if (CGM.getLangOpts().CUDA) {
605  // Emit NULL for methods we can't codegen on this
606  // side. Otherwise we'd end up with vtable with unresolved
607  // references.
608  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
609  // OK on device side: functions w/ __device__ attribute
610  // OK on host side: anything except __device__-only functions.
611  bool CanEmitMethod =
612  CGM.getLangOpts().CUDAIsDevice
613  ? MD->hasAttr<CUDADeviceAttr>()
614  : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
615  if (!CanEmitMethod)
616  return builder.addNullPointer(CGM.Int8PtrTy);
617  // Method is acceptable, continue processing as usual.
618  }
619 
620  auto getSpecialVirtualFn = [&](StringRef name) {
621  llvm::FunctionType *fnTy =
622  llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
623  llvm::Constant *fn = CGM.CreateRuntimeFunction(fnTy, name);
624  if (auto f = dyn_cast<llvm::Function>(fn))
625  f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
626  return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
627  };
628 
629  llvm::Constant *fnPtr;
630 
631  // Pure virtual member functions.
632  if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
633  if (!PureVirtualFn)
634  PureVirtualFn =
635  getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
636  fnPtr = PureVirtualFn;
637 
638  // Deleted virtual member functions.
639  } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
640  if (!DeletedVirtualFn)
641  DeletedVirtualFn =
642  getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
643  fnPtr = DeletedVirtualFn;
644 
645  // Thunks.
646  } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
647  layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
648  auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
649 
650  maybeEmitThunkForVTable(GD, thunkInfo);
651  nextVTableThunkIndex++;
652  fnPtr = CGM.GetAddrOfThunk(GD, thunkInfo);
653 
654  // Otherwise we can use the method definition directly.
655  } else {
656  llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
657  fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
658  }
659 
660  fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
661  builder.add(fnPtr);
662  return;
663  }
664 
666  return builder.addNullPointer(CGM.Int8PtrTy);
667  }
668 
669  llvm_unreachable("Unexpected vtable component kind");
670 }
671 
674  for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
675  tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
676  }
677 
678  return llvm::StructType::get(CGM.getLLVMContext(), tys);
679 }
680 
682  const VTableLayout &layout,
683  llvm::Constant *rtti) {
684  unsigned nextVTableThunkIndex = 0;
685  for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
686  auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
687  size_t thisIndex = layout.getVTableOffset(i);
688  size_t nextIndex = thisIndex + layout.getVTableSize(i);
689  for (unsigned i = thisIndex; i != nextIndex; ++i) {
690  addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
691  }
692  vtableElem.finishAndAddTo(builder);
693  }
694 }
695 
696 llvm::GlobalVariable *
698  const BaseSubobject &Base,
699  bool BaseIsVirtual,
700  llvm::GlobalVariable::LinkageTypes Linkage,
701  VTableAddressPointsMapTy& AddressPoints) {
702  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
703  DI->completeClassData(Base.getBase());
704 
705  std::unique_ptr<VTableLayout> VTLayout(
706  getItaniumVTableContext().createConstructionVTableLayout(
707  Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
708 
709  // Add the address points.
710  AddressPoints = VTLayout->getAddressPoints();
711 
712  // Get the mangled construction vtable name.
713  SmallString<256> OutName;
714  llvm::raw_svector_ostream Out(OutName);
715  cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
716  .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
717  Base.getBase(), Out);
718  StringRef Name = OutName.str();
719 
720  llvm::Type *VTType = getVTableType(*VTLayout);
721 
722  // Construction vtable symbols are not part of the Itanium ABI, so we cannot
723  // guarantee that they actually will be available externally. Instead, when
724  // emitting an available_externally VTT, we provide references to an internal
725  // linkage construction vtable. The ABI only requires complete-object vtables
726  // to be the same for all instances of a type, not construction vtables.
727  if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
729 
730  // Create the variable that will hold the construction vtable.
731  llvm::GlobalVariable *VTable =
732  CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage);
733  CGM.setGlobalVisibility(VTable, RD, ForDefinition);
734 
735  // V-tables are always unnamed_addr.
736  VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
737 
738  llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
739  CGM.getContext().getTagDeclType(Base.getBase()));
740 
741  // Create and set the initializer.
742  ConstantInitBuilder builder(CGM);
743  auto components = builder.beginStruct();
744  createVTableInitializer(components, *VTLayout, RTTI);
745  components.finishAndSetAsInitializer(VTable);
746 
747  CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
748 
749  return VTable;
750 }
751 
753  const CXXRecordDecl *RD) {
754  return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
756 }
757 
758 /// Compute the required linkage of the vtable for the given class.
759 ///
760 /// Note that we only call this at the end of the translation unit.
761 llvm::GlobalVariable::LinkageTypes
763  if (!RD->isExternallyVisible())
765 
766  // We're at the end of the translation unit, so the current key
767  // function is fully correct.
768  const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
769  if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
770  // If this class has a key function, use that to determine the
771  // linkage of the vtable.
772  const FunctionDecl *def = nullptr;
773  if (keyFunction->hasBody(def))
774  keyFunction = cast<CXXMethodDecl>(def);
775 
776  switch (keyFunction->getTemplateSpecializationKind()) {
777  case TSK_Undeclared:
779  assert((def || CodeGenOpts.OptimizationLevel > 0 ||
780  CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
781  "Shouldn't query vtable linkage without key function, "
782  "optimizations, or debug info");
783  if (!def && CodeGenOpts.OptimizationLevel > 0)
784  return llvm::GlobalVariable::AvailableExternallyLinkage;
785 
786  if (keyFunction->isInlined())
787  return !Context.getLangOpts().AppleKext ?
788  llvm::GlobalVariable::LinkOnceODRLinkage :
790 
792 
794  return !Context.getLangOpts().AppleKext ?
795  llvm::GlobalVariable::LinkOnceODRLinkage :
797 
799  return !Context.getLangOpts().AppleKext ?
800  llvm::GlobalVariable::WeakODRLinkage :
802 
804  llvm_unreachable("Should not have been asked to emit this");
805  }
806  }
807 
808  // -fapple-kext mode does not support weak linkage, so we must use
809  // internal linkage.
810  if (Context.getLangOpts().AppleKext)
812 
813  llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
814  llvm::GlobalValue::LinkOnceODRLinkage;
815  llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
816  llvm::GlobalValue::WeakODRLinkage;
817  if (RD->hasAttr<DLLExportAttr>()) {
818  // Cannot discard exported vtables.
819  DiscardableODRLinkage = NonDiscardableODRLinkage;
820  } else if (RD->hasAttr<DLLImportAttr>()) {
821  // Imported vtables are available externally.
822  DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
823  NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
824  }
825 
826  switch (RD->getTemplateSpecializationKind()) {
827  case TSK_Undeclared:
830  return DiscardableODRLinkage;
831 
833  // Explicit instantiations in MSVC do not provide vtables, so we must emit
834  // our own.
835  if (getTarget().getCXXABI().isMicrosoft())
836  return DiscardableODRLinkage;
837  return shouldEmitAvailableExternallyVTable(*this, RD)
838  ? llvm::GlobalVariable::AvailableExternallyLinkage
840 
842  return NonDiscardableODRLinkage;
843  }
844 
845  llvm_unreachable("Invalid TemplateSpecializationKind!");
846 }
847 
848 /// This is a callback from Sema to tell us that that a particular vtable is
849 /// required to be emitted in this translation unit.
850 ///
851 /// This is only called for vtables that _must_ be emitted (mainly due to key
852 /// functions). For weak vtables, CodeGen tracks when they are needed and
853 /// emits them as-needed.
855  VTables.GenerateClassData(theClass);
856 }
857 
858 void
860  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
861  DI->completeClassData(RD);
862 
863  if (RD->getNumVBases())
865 
866  CGM.getCXXABI().emitVTableDefinitions(*this, RD);
867 }
868 
869 /// At this point in the translation unit, does it appear that can we
870 /// rely on the vtable being defined elsewhere in the program?
871 ///
872 /// The response is really only definitive when called at the end of
873 /// the translation unit.
874 ///
875 /// The only semantic restriction here is that the object file should
876 /// not contain a vtable definition when that vtable is defined
877 /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
878 /// vtables when unnecessary.
880  assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
881 
882  // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
883  // emit them even if there is an explicit template instantiation.
884  if (CGM.getTarget().getCXXABI().isMicrosoft())
885  return false;
886 
887  // If we have an explicit instantiation declaration (and not a
888  // definition), the vtable is defined elsewhere.
891  return true;
892 
893  // Otherwise, if the class is an instantiated template, the
894  // vtable must be defined here.
895  if (TSK == TSK_ImplicitInstantiation ||
897  return false;
898 
899  // Otherwise, if the class doesn't have a key function (possibly
900  // anymore), the vtable must be defined here.
901  const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
902  if (!keyFunction)
903  return false;
904 
905  // Otherwise, if we don't have a definition of the key function, the
906  // vtable must be defined somewhere else.
907  return !keyFunction->hasBody();
908 }
909 
910 /// Given that we're currently at the end of the translation unit, and
911 /// we've emitted a reference to the vtable for this class, should
912 /// we define that vtable?
914  const CXXRecordDecl *RD) {
915  // If vtable is internal then it has to be done.
916  if (!CGM.getVTables().isVTableExternal(RD))
917  return true;
918 
919  // If it's external then maybe we will need it as available_externally.
920  return shouldEmitAvailableExternallyVTable(CGM, RD);
921 }
922 
923 /// Given that at some point we emitted a reference to one or more
924 /// vtables, and that we are now at the end of the translation unit,
925 /// decide whether we should emit them.
926 void CodeGenModule::EmitDeferredVTables() {
927 #ifndef NDEBUG
928  // Remember the size of DeferredVTables, because we're going to assume
929  // that this entire operation doesn't modify it.
930  size_t savedSize = DeferredVTables.size();
931 #endif
932 
933  for (const CXXRecordDecl *RD : DeferredVTables)
935  VTables.GenerateClassData(RD);
936  else if (shouldOpportunisticallyEmitVTables())
937  OpportunisticVTables.push_back(RD);
938 
939  assert(savedSize == DeferredVTables.size() &&
940  "deferred extra vtables during vtable emission?");
941  DeferredVTables.clear();
942 }
943 
946  if (!isExternallyVisible(LV.getLinkage()))
947  return true;
948 
949  if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
950  return false;
951 
952  if (getTriple().isOSBinFormatCOFF()) {
953  if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
954  return false;
955  } else {
956  if (LV.getVisibility() != HiddenVisibility)
957  return false;
958  }
959 
960  if (getCodeGenOpts().LTOVisibilityPublicStd) {
961  const DeclContext *DC = RD;
962  while (1) {
963  auto *D = cast<Decl>(DC);
964  DC = DC->getParent();
965  if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
966  if (auto *ND = dyn_cast<NamespaceDecl>(D))
967  if (const IdentifierInfo *II = ND->getIdentifier())
968  if (II->isStr("std") || II->isStr("stdext"))
969  return false;
970  break;
971  }
972  }
973  }
974 
975  return true;
976 }
977 
978 void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
979  const VTableLayout &VTLayout) {
980  if (!getCodeGenOpts().LTOUnit)
981  return;
982 
983  CharUnits PointerWidth =
984  Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
985 
986  typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
987  std::vector<BSEntry> BitsetEntries;
988  // Create a bit set entry for each address point.
989  for (auto &&AP : VTLayout.getAddressPoints())
990  BitsetEntries.push_back(
991  std::make_pair(AP.first.getBase(),
992  VTLayout.getVTableOffset(AP.second.VTableIndex) +
993  AP.second.AddressPointIndex));
994 
995  // Sort the bit set entries for determinism.
996  std::sort(BitsetEntries.begin(), BitsetEntries.end(),
997  [this](const BSEntry &E1, const BSEntry &E2) {
998  if (&E1 == &E2)
999  return false;
1000 
1001  std::string S1;
1002  llvm::raw_string_ostream O1(S1);
1003  getCXXABI().getMangleContext().mangleTypeName(
1004  QualType(E1.first->getTypeForDecl(), 0), O1);
1005  O1.flush();
1006 
1007  std::string S2;
1008  llvm::raw_string_ostream O2(S2);
1009  getCXXABI().getMangleContext().mangleTypeName(
1010  QualType(E2.first->getTypeForDecl(), 0), O2);
1011  O2.flush();
1012 
1013  if (S1 < S2)
1014  return true;
1015  if (S1 != S2)
1016  return false;
1017 
1018  return E1.second < E2.second;
1019  });
1020 
1021  for (auto BitsetEntry : BitsetEntries)
1022  AddVTableTypeMetadata(VTable, PointerWidth * BitsetEntry.second,
1023  BitsetEntry.first);
1024 }
size_t getNumVTables() const
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:281
static const Decl * getCanonicalDecl(const Decl *D)
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1698
External linkage, which indicates that the entity can be referred to from other translation units...
Definition: Linkage.h:61
CanQualType VoidPtrTy
Definition: ASTContext.h:1012
A (possibly-)qualified type.
Definition: Type.h:653
bool ReturnTypeUsesSRet(const CGFunctionInfo &FI)
Return true iff the given type uses &#39;sret&#39; when used as a return type.
Definition: CGCall.cpp:1481
const CodeGenOptions & getCodeGenOpts() const
const AddressPointsMapTy & getAddressPoints() const
virtual void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResultType)
Definition: CGCXXABI.cpp:163
llvm::LLVMContext & getLLVMContext()
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:71
virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params)=0
Insert any ABI-specific implicit parameters into the parameter list for a function.
The standard implementation of ConstantInitBuilder used in Clang.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
Definition: CGClass.cpp:36
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3058
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:456
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:788
bool isEmpty() const
Definition: ABI.h:87
virtual const ThunkInfoVectorTy * getThunkInfo(GlobalDecl GD)
virtual llvm::Value * performThisAdjustment(CodeGenFunction &CGF, Address This, const ThisAdjustment &TA)=0
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
virtual StringRef GetDeletedVirtualCallName()=0
Gets the deleted virtual member call name.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:671
llvm::Function * GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk)
Definition: CGVTables.cpp:170
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i...
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
Definition: CGVTables.cpp:944
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:35
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6307
Visibility getVisibility() const
Definition: Visibility.h:83
CGDebugInfo * getModuleDebugInfo()
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:53
llvm::Value * getPointer() const
Definition: Address.h:38
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1514
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:25
CharUnits getBaseOffset() const
getBaseOffset - Returns the base class offset.
Definition: BaseSubobject.h:46
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:311
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:859
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM, const CXXRecordDecl *RD)
Definition: CGVTables.cpp:752
static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD, const ThunkInfo &Thunk, llvm::Function *Fn)
Definition: CGVTables.cpp:52
bool isReferenceType() const
Definition: Type.h:5956
static void resolveTopLevelMetadata(llvm::Function *Fn, llvm::ValueToValueMapTy &VMap)
This function clones a function&#39;s DISubprogram node and enters it into a value map with the intent th...
Definition: CGVTables.cpp:131
llvm::Type * getVTableType(const VTableLayout &layout)
Returns the type of a vtable with the given layout.
Definition: CGVTables.cpp:672
The this pointer adjustment as well as an optional return adjustment for a thunk. ...
Definition: ABI.h:179
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:651
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2164
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
ArrayRef< VTableComponent > vtable_components() const
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
Definition: DeclCXX.cpp:1934
virtual void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD)=0
Emits the VTable definitions required for the given record type.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
Deleting dtor.
Definition: ABI.h:35
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:109
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5790
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite)
Get the LLVM attributes and calling convention to use for a particular function type.
Definition: CGCall.cpp:1780
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D, ForDefinition_t IsForDefinition) const
Set the visibility for the given LLVM GlobalValue.
virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const =0
Determine whether it&#39;s possible to emit a vtable for RD, even though we do not know that the vtable h...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
ItaniumVTableContext & getItaniumVTableContext()
Definition: CGVTables.h:81
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:497
param_iterator param_begin()
Definition: Decl.h:2176
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
bool hasAttr() const
Definition: DeclBase.h:535
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1590
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3270
bool isDynamicClass() const
Definition: DeclCXX.h:751
ArrayBuilder beginArray(llvm::Type *eltTy=nullptr)
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1386
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:39
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
bool isVTableExternal(const CXXRecordDecl *RD)
At this point in the translation unit, does it appear that can we rely on the vtable being defined el...
Definition: CGVTables.cpp:879
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns &#39;th...
Definition: CGCXXABI.h:107
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
Definition: TargetCXXABI.h:234
static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk, llvm::Function *ThunkFn, bool ForVTable, GlobalDecl GD)
Definition: CGVTables.cpp:57
static bool similar(const ABIArgInfo &infoL, CanQualType typeL, const ABIArgInfo &infoR, CanQualType typeR)
Definition: CGVTables.cpp:73
const FunctionProtoType * T
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6370
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:125
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2620
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
virtual StringRef GetPureVirtualCallName()=0
Gets the pure virtual member call function.
Linkage getLinkage() const
Definition: Visibility.h:82
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:207
const CXXRecordDecl * getBase() const
getBase - Returns the base class declaration.
Definition: BaseSubobject.h:43
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body (definition).
Definition: Decl.cpp:2576
Base object dtor.
Definition: ABI.h:37
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1331
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:87
const TargetInfo & getTarget() const
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:149
const LangOptions & getLangOpts() const
ASTContext & getContext() const
virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, CallArgList &CallArgs)
Definition: CGCXXABI.h:428
void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk)
Generate a thunk for the given method.
Definition: CGVTables.cpp:431
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:233
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:35
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage)
Will return a global variable of the given type.
llvm::Constant * GetAddrOfThunk(GlobalDecl GD, const ThunkInfo &Thunk)
Get the address of the thunk for the given global decl.
Definition: CGVTables.cpp:34
The l-value was considered opaque, so the alignment was determined from a type.
ArrayRef< VTableThunkTy > vtable_thunks() const
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3203
const Decl * getDecl() const
Definition: GlobalDecl.h:64
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1964
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
CodeGenVTables(CodeGenModule &CGM)
Definition: CGVTables.cpp:31
void createVTableInitializer(ConstantStructBuilder &builder, const VTableLayout &layout, llvm::Constant *rtti)
Add vtable components for the given vtable layout to the given global initializer.
Definition: CGVTables.cpp:681
An aligned address.
Definition: Address.h:25
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD)=0
Emit any tables needed to implement virtual inheritance.
All available information about a concrete callee.
Definition: CGCall.h:66
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:97
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:161
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:146
Complete object dtor.
Definition: ABI.h:36
llvm::GlobalVariable * GenerateConstructionVTable(const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual, llvm::GlobalVariable::LinkageTypes Linkage, VTableAddressPointsMapTy &AddressPoints)
GenerateConstructionVTable - Generate a construction vtable for the given base subobject.
Definition: CGVTables.cpp:697
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:276
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:59
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn&#39;t support the specified stmt yet.
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
Dataflow Directional Tag Classes.
ThisAdjustment This
The this pointer adjustment.
Definition: ABI.h:181
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1252
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3426
void EmitVTableTypeMetadata(llvm::GlobalVariable *VTable, const VTableLayout &VTLayout)
Emit type metadata for the given vtable using the given layout.
Definition: CGVTables.cpp:978
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:157
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2085
void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params)
Build a parameter variable suitable for &#39;this&#39;.
Definition: CGCXXABI.cpp:128
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:143
llvm::Module & getModule() const
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
Definition: CGVTables.cpp:541
param_iterator param_end()
Definition: Decl.h:2177
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class...
Definition: CGVTables.cpp:762
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
Definition: Decl.cpp:1050
StructBuilder beginStruct(llvm::StructType *structTy=nullptr)
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:153
static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM, const CXXRecordDecl *RD)
Given that we&#39;re currently at the end of the translation unit, and we&#39;ve emitted a reference to the v...
Definition: CGVTables.cpp:913
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
Definition: CGVTables.cpp:859
ReturnAdjustment Return
The return adjustment.
Definition: ABI.h:184
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:436
void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo)
Definition: CGVTables.cpp:238
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2255
llvm::Type * GetFunctionTypeForVTable(GlobalDecl GD)
GetFunctionTypeForVTable - Get the LLVM function type for use in a vtable, given a CXXMethodDecl...
Definition: CGCall.cpp:1652
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void EmitCallAndReturnForThunk(llvm::Constant *Callee, const ThunkInfo *Thunk)
Definition: CGVTables.cpp:287
static RValue PerformReturnAdjustment(CodeGenFunction &CGF, QualType ResultType, RValue RV, const ThunkInfo &Thunk)
Definition: CGVTables.cpp:82
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn&#39;t on...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
bool isVoidType() const
Definition: Type.h:6171
A helper class of ConstantInitBuilder, used for building constant struct initializers.
size_t getVTableSize(size_t i) const
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
A pointer to the deleting destructor.
Definition: VTableBuilder.h:43
CGCXXABI & getCXXABI() const
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional, const FunctionDecl *FD)
Compute the arguments required by the given formal prototype, given that there may be some additional...
virtual llvm::Value * performReturnAdjustment(CodeGenFunction &CGF, Address Ret, const ReturnAdjustment &RA)=0
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
Definition: CGDebugInfo.h:668
QualType getType() const
Definition: Decl.h:639
CodeGenVTables & getVTables()
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:182
const CGFunctionInfo & arrangeCXXMethodCall(const CallArgList &args, const FunctionProtoType *type, RequiredArgs required, unsigned numPrefixArgs)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:662
const LangOptions & getLangOpts() const
Definition: ASTContext.h:688
A pointer to the complete destructor.
Definition: VTableBuilder.h:40
A helper class of ConstantInitBuilder, used for building constant array initializers.
size_t getVTableOffset(size_t i) const
virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, bool ReturnAdjustment)=0
SourceLocation getLocation() const
Definition: DeclBase.h:416
bool isExternallyVisible() const
Definition: Decl.h:371
void EmitVTable(CXXRecordDecl *Class)
This is a callback from Sema to tell us that that a particular vtable is required to be emitted in th...
Definition: CGVTables.cpp:854
void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr, llvm::Value *Callee)
Emit a musttail call for a thunk with a potentially adjusted this pointer.
Definition: CGVTables.cpp:378
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1524