clang  10.0.0git
CGVTables.cpp
Go to the documentation of this file.
1 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code dealing with C++ code generation of virtual tables.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCXXABI.h"
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/Attr.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 
34 llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
35  GlobalDecl GD) {
36  return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
37  /*DontDefer=*/true, /*IsThunk=*/true);
38 }
39 
40 static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
41  llvm::Function *ThunkFn, bool ForVTable,
42  GlobalDecl GD) {
43  CGM.setFunctionLinkage(GD, ThunkFn);
44  CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
45  !Thunk.Return.isEmpty());
46 
47  // Set the right visibility.
48  CGM.setGVProperties(ThunkFn, GD);
49 
50  if (!CGM.getCXXABI().exportThunk()) {
51  ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
52  ThunkFn->setDSOLocal(true);
53  }
54 
55  if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
56  ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
57 }
58 
59 #ifndef NDEBUG
60 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61  const ABIArgInfo &infoR, CanQualType typeR) {
62  return (infoL.getKind() == infoR.getKind() &&
63  (typeL == typeR ||
64  (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
65  (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
66 }
67 #endif
68 
70  QualType ResultType, RValue RV,
71  const ThunkInfo &Thunk) {
72  // Emit the return adjustment.
73  bool NullCheckValue = !ResultType->isReferenceType();
74 
75  llvm::BasicBlock *AdjustNull = nullptr;
76  llvm::BasicBlock *AdjustNotNull = nullptr;
77  llvm::BasicBlock *AdjustEnd = nullptr;
78 
80 
81  if (NullCheckValue) {
82  AdjustNull = CGF.createBasicBlock("adjust.null");
83  AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
84  AdjustEnd = CGF.createBasicBlock("adjust.end");
85 
86  llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87  CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88  CGF.EmitBlock(AdjustNotNull);
89  }
90 
91  auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
92  auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
93  ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
94  Address(ReturnValue, ClassAlign),
95  Thunk.Return);
96 
97  if (NullCheckValue) {
98  CGF.Builder.CreateBr(AdjustEnd);
99  CGF.EmitBlock(AdjustNull);
100  CGF.Builder.CreateBr(AdjustEnd);
101  CGF.EmitBlock(AdjustEnd);
102 
103  llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
104  PHI->addIncoming(ReturnValue, AdjustNotNull);
105  PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
106  AdjustNull);
107  ReturnValue = PHI;
108  }
109 
110  return RValue::get(ReturnValue);
111 }
112 
113 /// This function clones a function's DISubprogram node and enters it into
114 /// a value map with the intent that the map can be utilized by the cloner
115 /// to short-circuit Metadata node mapping.
116 /// Furthermore, the function resolves any DILocalVariable nodes referenced
117 /// by dbg.value intrinsics so they can be properly mapped during cloning.
118 static void resolveTopLevelMetadata(llvm::Function *Fn,
119  llvm::ValueToValueMapTy &VMap) {
120  // Clone the DISubprogram node and put it into the Value map.
121  auto *DIS = Fn->getSubprogram();
122  if (!DIS)
123  return;
124  auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
125  VMap.MD()[DIS].reset(NewDIS);
126 
127  // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
128  // they are referencing.
129  for (auto &BB : Fn->getBasicBlockList()) {
130  for (auto &I : BB) {
131  if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
132  auto *DILocal = DII->getVariable();
133  if (!DILocal->isResolved())
134  DILocal->resolve();
135  }
136  }
137  }
138 }
139 
140 // This function does roughly the same thing as GenerateThunk, but in a
141 // very different way, so that va_start and va_end work correctly.
142 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
143 // a function, and that there is an alloca built in the entry block
144 // for all accesses to "this".
145 // FIXME: This function assumes there is only one "ret" statement per function.
146 // FIXME: Cloning isn't correct in the presence of indirect goto!
147 // FIXME: This implementation of thunks bloats codesize by duplicating the
148 // function definition. There are alternatives:
149 // 1. Add some sort of stub support to LLVM for cases where we can
150 // do a this adjustment, then a sibcall.
151 // 2. We could transform the definition to take a va_list instead of an
152 // actual variable argument list, then have the thunks (including a
153 // no-op thunk for the regular definition) call va_start/va_end.
154 // There's a bit of per-call overhead for this solution, but it's
155 // better for codesize if the definition is long.
156 llvm::Function *
158  const CGFunctionInfo &FnInfo,
159  GlobalDecl GD, const ThunkInfo &Thunk) {
160  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
161  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
162  QualType ResultType = FPT->getReturnType();
163 
164  // Get the original function
165  assert(FnInfo.isVariadic());
166  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
167  llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
168  llvm::Function *BaseFn = cast<llvm::Function>(Callee);
169 
170  // Cloning can't work if we don't have a definition. The Microsoft ABI may
171  // require thunks when a definition is not available. Emit an error in these
172  // cases.
173  if (!MD->isDefined()) {
174  CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
175  return Fn;
176  }
177  assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
178 
179  // Clone to thunk.
180  llvm::ValueToValueMapTy VMap;
181 
182  // We are cloning a function while some Metadata nodes are still unresolved.
183  // Ensure that the value mapper does not encounter any of them.
184  resolveTopLevelMetadata(BaseFn, VMap);
185  llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
186  Fn->replaceAllUsesWith(NewFn);
187  NewFn->takeName(Fn);
188  Fn->eraseFromParent();
189  Fn = NewFn;
190 
191  // "Initialize" CGF (minimally).
192  CurFn = Fn;
193 
194  // Get the "this" value
195  llvm::Function::arg_iterator AI = Fn->arg_begin();
196  if (CGM.ReturnTypeUsesSRet(FnInfo))
197  ++AI;
198 
199  // Find the first store of "this", which will be to the alloca associated
200  // with "this".
201  Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
202  llvm::BasicBlock *EntryBB = &Fn->front();
203  llvm::BasicBlock::iterator ThisStore =
204  std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
205  return isa<llvm::StoreInst>(I) &&
206  I.getOperand(0) == ThisPtr.getPointer();
207  });
208  assert(ThisStore != EntryBB->end() &&
209  "Store of this should be in entry block?");
210  // Adjust "this", if necessary.
211  Builder.SetInsertPoint(&*ThisStore);
212  llvm::Value *AdjustedThisPtr =
213  CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
214  AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
215  ThisStore->getOperand(0)->getType());
216  ThisStore->setOperand(0, AdjustedThisPtr);
217 
218  if (!Thunk.Return.isEmpty()) {
219  // Fix up the returned value, if necessary.
220  for (llvm::BasicBlock &BB : *Fn) {
221  llvm::Instruction *T = BB.getTerminator();
222  if (isa<llvm::ReturnInst>(T)) {
223  RValue RV = RValue::get(T->getOperand(0));
224  T->eraseFromParent();
225  Builder.SetInsertPoint(&BB);
226  RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
227  Builder.CreateRet(RV.getScalarVal());
228  break;
229  }
230  }
231  }
232 
233  return Fn;
234 }
235 
236 void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
237  const CGFunctionInfo &FnInfo,
238  bool IsUnprototyped) {
239  assert(!CurGD.getDecl() && "CurGD was already set!");
240  CurGD = GD;
241  CurFuncIsThunk = true;
242 
243  // Build FunctionArgs.
244  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
245  QualType ThisType = MD->getThisType();
246  QualType ResultType;
247  if (IsUnprototyped)
248  ResultType = CGM.getContext().VoidTy;
249  else if (CGM.getCXXABI().HasThisReturn(GD))
250  ResultType = ThisType;
251  else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
252  ResultType = CGM.getContext().VoidPtrTy;
253  else
254  ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
255  FunctionArgList FunctionArgs;
256 
257  // Create the implicit 'this' parameter declaration.
258  CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
259 
260  // Add the rest of the parameters, if we have a prototype to work with.
261  if (!IsUnprototyped) {
262  FunctionArgs.append(MD->param_begin(), MD->param_end());
263 
264  if (isa<CXXDestructorDecl>(MD))
265  CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
266  FunctionArgs);
267  }
268 
269  // Start defining the function.
270  auto NL = ApplyDebugLocation::CreateEmpty(*this);
271  StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
272  MD->getLocation());
273  // Create a scope with an artificial location for the body of this function.
274  auto AL = ApplyDebugLocation::CreateArtificial(*this);
275 
276  // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
278  CXXThisValue = CXXABIThisValue;
279  CurCodeDecl = MD;
280  CurFuncDecl = MD;
281 }
282 
284  // Clear these to restore the invariants expected by
285  // StartFunction/FinishFunction.
286  CurCodeDecl = nullptr;
287  CurFuncDecl = nullptr;
288 
289  FinishFunction();
290 }
291 
292 void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
293  const ThunkInfo *Thunk,
294  bool IsUnprototyped) {
295  assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
296  "Please use a new CGF for this thunk");
297  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
298 
299  // Adjust the 'this' pointer if necessary
300  llvm::Value *AdjustedThisPtr =
301  Thunk ? CGM.getCXXABI().performThisAdjustment(
302  *this, LoadCXXThisAddress(), Thunk->This)
303  : LoadCXXThis();
304 
305  // If perfect forwarding is required a variadic method, a method using
306  // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
307  // thunk requires a return adjustment, since that is impossible with musttail.
308  if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
309  if (Thunk && !Thunk->Return.isEmpty()) {
310  if (IsUnprototyped)
311  CGM.ErrorUnsupported(
312  MD, "return-adjusting thunk with incomplete parameter type");
313  else if (CurFnInfo->isVariadic())
314  llvm_unreachable("shouldn't try to emit musttail return-adjusting "
315  "thunks for variadic functions");
316  else
317  CGM.ErrorUnsupported(
318  MD, "non-trivial argument copy for return-adjusting thunk");
319  }
320  EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
321  return;
322  }
323 
324  // Start building CallArgs.
325  CallArgList CallArgs;
326  QualType ThisType = MD->getThisType();
327  CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
328 
329  if (isa<CXXDestructorDecl>(MD))
330  CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
331 
332 #ifndef NDEBUG
333  unsigned PrefixArgs = CallArgs.size() - 1;
334 #endif
335  // Add the rest of the arguments.
336  for (const ParmVarDecl *PD : MD->parameters())
337  EmitDelegateCallArg(CallArgs, PD, SourceLocation());
338 
339  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
340 
341 #ifndef NDEBUG
342  const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
343  CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
344  assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
345  CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
346  CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
347  assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
348  similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
349  CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
350  assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
351  for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
352  assert(similar(CallFnInfo.arg_begin()[i].info,
353  CallFnInfo.arg_begin()[i].type,
354  CurFnInfo->arg_begin()[i].info,
355  CurFnInfo->arg_begin()[i].type));
356 #endif
357 
358  // Determine whether we have a return value slot to use.
359  QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
360  ? ThisType
361  : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
362  ? CGM.getContext().VoidPtrTy
363  : FPT->getReturnType();
364  ReturnValueSlot Slot;
365  if (!ResultType->isVoidType() &&
366  CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect)
367  Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
368 
369  // Now emit our call.
370  llvm::CallBase *CallOrInvoke;
371  RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
372  CallArgs, &CallOrInvoke);
373 
374  // Consider return adjustment if we have ThunkInfo.
375  if (Thunk && !Thunk->Return.isEmpty())
376  RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
377  else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
378  Call->setTailCallKind(llvm::CallInst::TCK_Tail);
379 
380  // Emit return.
381  if (!ResultType->isVoidType() && Slot.isNull())
382  CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
383 
384  // Disable the final ARC autorelease.
385  AutoreleaseResult = false;
386 
387  FinishThunk();
388 }
389 
391  llvm::Value *AdjustedThisPtr,
392  llvm::FunctionCallee Callee) {
393  // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
394  // to translate AST arguments into LLVM IR arguments. For thunks, we know
395  // that the caller prototype more or less matches the callee prototype with
396  // the exception of 'this'.
398  for (llvm::Argument &A : CurFn->args())
399  Args.push_back(&A);
400 
401  // Set the adjusted 'this' pointer.
402  const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
403  if (ThisAI.isDirect()) {
404  const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
405  int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
406  llvm::Type *ThisType = Args[ThisArgNo]->getType();
407  if (ThisType != AdjustedThisPtr->getType())
408  AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
409  Args[ThisArgNo] = AdjustedThisPtr;
410  } else {
411  assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
412  Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
413  llvm::Type *ThisType = ThisAddr.getElementType();
414  if (ThisType != AdjustedThisPtr->getType())
415  AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
416  Builder.CreateStore(AdjustedThisPtr, ThisAddr);
417  }
418 
419  // Emit the musttail call manually. Even if the prologue pushed cleanups, we
420  // don't actually want to run them.
421  llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
422  Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
423 
424  // Apply the standard set of call attributes.
425  unsigned CallingConv;
426  llvm::AttributeList Attrs;
427  CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
428  Attrs, CallingConv, /*AttrOnCallSite=*/true);
429  Call->setAttributes(Attrs);
430  Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
431 
432  if (Call->getType()->isVoidTy())
433  Builder.CreateRetVoid();
434  else
435  Builder.CreateRet(Call);
436 
437  // Finish the function to maintain CodeGenFunction invariants.
438  // FIXME: Don't emit unreachable code.
439  EmitBlock(createBasicBlock());
440  FinishFunction();
441 }
442 
443 void CodeGenFunction::generateThunk(llvm::Function *Fn,
444  const CGFunctionInfo &FnInfo, GlobalDecl GD,
445  const ThunkInfo &Thunk,
446  bool IsUnprototyped) {
447  StartThunk(Fn, GD, FnInfo, IsUnprototyped);
448  // Create a scope with an artificial location for the body of this function.
449  auto AL = ApplyDebugLocation::CreateArtificial(*this);
450 
451  // Get our callee. Use a placeholder type if this method is unprototyped so
452  // that CodeGenModule doesn't try to set attributes.
453  llvm::Type *Ty;
454  if (IsUnprototyped)
455  Ty = llvm::StructType::get(getLLVMContext());
456  else
457  Ty = CGM.getTypes().GetFunctionType(FnInfo);
458 
459  llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
460 
461  // Fix up the function type for an unprototyped musttail call.
462  if (IsUnprototyped)
463  Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
464 
465  // Make the call and return the result.
466  EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
467  &Thunk, IsUnprototyped);
468 }
469 
471  bool IsUnprototyped, bool ForVTable) {
472  // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
473  // provide thunks for us.
474  if (CGM.getTarget().getCXXABI().isMicrosoft())
475  return true;
476 
477  // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
478  // definitions of the main method. Therefore, emitting thunks with the vtable
479  // is purely an optimization. Emit the thunk if optimizations are enabled and
480  // all of the parameter types are complete.
481  if (ForVTable)
482  return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
483 
484  // Always emit thunks along with the method definition.
485  return true;
486 }
487 
488 llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
489  const ThunkInfo &TI,
490  bool ForVTable) {
491  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
492 
493  // First, get a declaration. Compute the mangled name. Don't worry about
494  // getting the function prototype right, since we may only need this
495  // declaration to fill in a vtable slot.
496  SmallString<256> Name;
497  MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
498  llvm::raw_svector_ostream Out(Name);
499  if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
500  MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
501  else
502  MCtx.mangleThunk(MD, TI, Out);
503  llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
504  llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
505 
506  // If we don't need to emit a definition, return this declaration as is.
507  bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
508  MD->getType()->castAs<FunctionType>());
509  if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
510  return Thunk;
511 
512  // Arrange a function prototype appropriate for a function definition. In some
513  // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
514  const CGFunctionInfo &FnInfo =
515  IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
517  llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
518 
519  // If the type of the underlying GlobalValue is wrong, we'll have to replace
520  // it. It should be a declaration.
521  llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
522  if (ThunkFn->getFunctionType() != ThunkFnTy) {
523  llvm::GlobalValue *OldThunkFn = ThunkFn;
524 
525  assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
526 
527  // Remove the name from the old thunk function and get a new thunk.
528  OldThunkFn->setName(StringRef());
530  Name.str(), &CGM.getModule());
531  CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
532 
533  // If needed, replace the old thunk with a bitcast.
534  if (!OldThunkFn->use_empty()) {
535  llvm::Constant *NewPtrForOldDecl =
536  llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
537  OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
538  }
539 
540  // Remove the old thunk.
541  OldThunkFn->eraseFromParent();
542  }
543 
544  bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
545  bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
546 
547  if (!ThunkFn->isDeclaration()) {
548  if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
549  // There is already a thunk emitted for this function, do nothing.
550  return ThunkFn;
551  }
552 
553  setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
554  return ThunkFn;
555  }
556 
557  // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
558  // that the return type is meaningless. These thunks can be used to call
559  // functions with differing return types, and the caller is required to cast
560  // the prototype appropriately to extract the correct value.
561  if (IsUnprototyped)
562  ThunkFn->addFnAttr("thunk");
563 
565 
566  // Thunks for variadic methods are special because in general variadic
567  // arguments cannot be perferctly forwarded. In the general case, clang
568  // implements such thunks by cloning the original function body. However, for
569  // thunks with no return adjustment on targets that support musttail, we can
570  // use musttail to perfectly forward the variadic arguments.
571  bool ShouldCloneVarArgs = false;
572  if (!IsUnprototyped && ThunkFn->isVarArg()) {
573  ShouldCloneVarArgs = true;
574  if (TI.Return.isEmpty()) {
575  switch (CGM.getTriple().getArch()) {
576  case llvm::Triple::x86_64:
577  case llvm::Triple::x86:
578  case llvm::Triple::aarch64:
579  ShouldCloneVarArgs = false;
580  break;
581  default:
582  break;
583  }
584  }
585  }
586 
587  if (ShouldCloneVarArgs) {
588  if (UseAvailableExternallyLinkage)
589  return ThunkFn;
590  ThunkFn =
591  CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
592  } else {
593  // Normal thunk body generation.
594  CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
595  }
596 
597  setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
598  return ThunkFn;
599 }
600 
602  const CXXMethodDecl *MD =
603  cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
604 
605  // We don't need to generate thunks for the base destructor.
606  if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
607  return;
608 
609  const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
610  VTContext->getThunkInfo(GD);
611 
612  if (!ThunkInfoVector)
613  return;
614 
615  for (const ThunkInfo& Thunk : *ThunkInfoVector)
616  maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
617 }
618 
619 void CodeGenVTables::addVTableComponent(
620  ConstantArrayBuilder &builder, const VTableLayout &layout,
621  unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
622  auto &component = layout.vtable_components()[idx];
623 
624  auto addOffsetConstant = [&](CharUnits offset) {
625  builder.add(llvm::ConstantExpr::getIntToPtr(
626  llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
627  CGM.Int8PtrTy));
628  };
629 
630  switch (component.getKind()) {
632  return addOffsetConstant(component.getVCallOffset());
633 
635  return addOffsetConstant(component.getVBaseOffset());
636 
638  return addOffsetConstant(component.getOffsetToTop());
639 
641  return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
642 
646  GlobalDecl GD;
647 
648  // Get the right global decl.
649  switch (component.getKind()) {
650  default:
651  llvm_unreachable("Unexpected vtable component kind");
653  GD = component.getFunctionDecl();
654  break;
656  GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
657  break;
659  GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
660  break;
661  }
662 
663  if (CGM.getLangOpts().CUDA) {
664  // Emit NULL for methods we can't codegen on this
665  // side. Otherwise we'd end up with vtable with unresolved
666  // references.
667  const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
668  // OK on device side: functions w/ __device__ attribute
669  // OK on host side: anything except __device__-only functions.
670  bool CanEmitMethod =
671  CGM.getLangOpts().CUDAIsDevice
672  ? MD->hasAttr<CUDADeviceAttr>()
673  : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
674  if (!CanEmitMethod)
675  return builder.addNullPointer(CGM.Int8PtrTy);
676  // Method is acceptable, continue processing as usual.
677  }
678 
679  auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
680  // For NVPTX devices in OpenMP emit special functon as null pointers,
681  // otherwise linking ends up with unresolved references.
682  if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPIsDevice &&
683  CGM.getTriple().isNVPTX())
684  return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
685  llvm::FunctionType *fnTy =
686  llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
687  llvm::Constant *fn = cast<llvm::Constant>(
688  CGM.CreateRuntimeFunction(fnTy, name).getCallee());
689  if (auto f = dyn_cast<llvm::Function>(fn))
690  f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
691  return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
692  };
693 
694  llvm::Constant *fnPtr;
695 
696  // Pure virtual member functions.
697  if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
698  if (!PureVirtualFn)
699  PureVirtualFn =
700  getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
701  fnPtr = PureVirtualFn;
702 
703  // Deleted virtual member functions.
704  } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
705  if (!DeletedVirtualFn)
706  DeletedVirtualFn =
707  getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
708  fnPtr = DeletedVirtualFn;
709 
710  // Thunks.
711  } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
712  layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
713  auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
714 
715  nextVTableThunkIndex++;
716  fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
717 
718  // Otherwise we can use the method definition directly.
719  } else {
720  llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
721  fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
722  }
723 
724  fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
725  builder.add(fnPtr);
726  return;
727  }
728 
730  return builder.addNullPointer(CGM.Int8PtrTy);
731  }
732 
733  llvm_unreachable("Unexpected vtable component kind");
734 }
735 
738  for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
739  tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
740  }
741 
742  return llvm::StructType::get(CGM.getLLVMContext(), tys);
743 }
744 
746  const VTableLayout &layout,
747  llvm::Constant *rtti) {
748  unsigned nextVTableThunkIndex = 0;
749  for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
750  auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
751  size_t thisIndex = layout.getVTableOffset(i);
752  size_t nextIndex = thisIndex + layout.getVTableSize(i);
753  for (unsigned i = thisIndex; i != nextIndex; ++i) {
754  addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
755  }
756  vtableElem.finishAndAddTo(builder);
757  }
758 }
759 
760 llvm::GlobalVariable *
762  const BaseSubobject &Base,
763  bool BaseIsVirtual,
764  llvm::GlobalVariable::LinkageTypes Linkage,
765  VTableAddressPointsMapTy& AddressPoints) {
766  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
767  DI->completeClassData(Base.getBase());
768 
769  std::unique_ptr<VTableLayout> VTLayout(
770  getItaniumVTableContext().createConstructionVTableLayout(
771  Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
772 
773  // Add the address points.
774  AddressPoints = VTLayout->getAddressPoints();
775 
776  // Get the mangled construction vtable name.
777  SmallString<256> OutName;
778  llvm::raw_svector_ostream Out(OutName);
779  cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
780  .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
781  Base.getBase(), Out);
782  StringRef Name = OutName.str();
783 
784  llvm::Type *VTType = getVTableType(*VTLayout);
785 
786  // Construction vtable symbols are not part of the Itanium ABI, so we cannot
787  // guarantee that they actually will be available externally. Instead, when
788  // emitting an available_externally VTT, we provide references to an internal
789  // linkage construction vtable. The ABI only requires complete-object vtables
790  // to be the same for all instances of a type, not construction vtables.
791  if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
793 
794  unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
795 
796  // Create the variable that will hold the construction vtable.
797  llvm::GlobalVariable *VTable =
798  CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
799 
800  // V-tables are always unnamed_addr.
801  VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
802 
803  llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
804  CGM.getContext().getTagDeclType(Base.getBase()));
805 
806  // Create and set the initializer.
807  ConstantInitBuilder builder(CGM);
808  auto components = builder.beginStruct();
809  createVTableInitializer(components, *VTLayout, RTTI);
810  components.finishAndSetAsInitializer(VTable);
811 
812  // Set properties only after the initializer has been set to ensure that the
813  // GV is treated as definition and not declaration.
814  assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
815  CGM.setGVProperties(VTable, RD);
816 
817  CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
818 
819  return VTable;
820 }
821 
823  const CXXRecordDecl *RD) {
824  return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
826 }
827 
828 /// Compute the required linkage of the vtable for the given class.
829 ///
830 /// Note that we only call this at the end of the translation unit.
831 llvm::GlobalVariable::LinkageTypes
833  if (!RD->isExternallyVisible())
835 
836  // We're at the end of the translation unit, so the current key
837  // function is fully correct.
838  const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
839  if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
840  // If this class has a key function, use that to determine the
841  // linkage of the vtable.
842  const FunctionDecl *def = nullptr;
843  if (keyFunction->hasBody(def))
844  keyFunction = cast<CXXMethodDecl>(def);
845 
846  switch (keyFunction->getTemplateSpecializationKind()) {
847  case TSK_Undeclared:
849  assert((def || CodeGenOpts.OptimizationLevel > 0 ||
850  CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
851  "Shouldn't query vtable linkage without key function, "
852  "optimizations, or debug info");
853  if (!def && CodeGenOpts.OptimizationLevel > 0)
854  return llvm::GlobalVariable::AvailableExternallyLinkage;
855 
856  if (keyFunction->isInlined())
857  return !Context.getLangOpts().AppleKext ?
858  llvm::GlobalVariable::LinkOnceODRLinkage :
860 
862 
864  return !Context.getLangOpts().AppleKext ?
865  llvm::GlobalVariable::LinkOnceODRLinkage :
867 
869  return !Context.getLangOpts().AppleKext ?
870  llvm::GlobalVariable::WeakODRLinkage :
872 
874  llvm_unreachable("Should not have been asked to emit this");
875  }
876  }
877 
878  // -fapple-kext mode does not support weak linkage, so we must use
879  // internal linkage.
880  if (Context.getLangOpts().AppleKext)
882 
883  llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
884  llvm::GlobalValue::LinkOnceODRLinkage;
885  llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
886  llvm::GlobalValue::WeakODRLinkage;
887  if (RD->hasAttr<DLLExportAttr>()) {
888  // Cannot discard exported vtables.
889  DiscardableODRLinkage = NonDiscardableODRLinkage;
890  } else if (RD->hasAttr<DLLImportAttr>()) {
891  // Imported vtables are available externally.
892  DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
893  NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
894  }
895 
896  switch (RD->getTemplateSpecializationKind()) {
897  case TSK_Undeclared:
900  return DiscardableODRLinkage;
901 
903  // Explicit instantiations in MSVC do not provide vtables, so we must emit
904  // our own.
905  if (getTarget().getCXXABI().isMicrosoft())
906  return DiscardableODRLinkage;
907  return shouldEmitAvailableExternallyVTable(*this, RD)
908  ? llvm::GlobalVariable::AvailableExternallyLinkage
910 
912  return NonDiscardableODRLinkage;
913  }
914 
915  llvm_unreachable("Invalid TemplateSpecializationKind!");
916 }
917 
918 /// This is a callback from Sema to tell us that a particular vtable is
919 /// required to be emitted in this translation unit.
920 ///
921 /// This is only called for vtables that _must_ be emitted (mainly due to key
922 /// functions). For weak vtables, CodeGen tracks when they are needed and
923 /// emits them as-needed.
925  VTables.GenerateClassData(theClass);
926 }
927 
928 void
930  if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
931  DI->completeClassData(RD);
932 
933  if (RD->getNumVBases())
935 
936  CGM.getCXXABI().emitVTableDefinitions(*this, RD);
937 }
938 
939 /// At this point in the translation unit, does it appear that can we
940 /// rely on the vtable being defined elsewhere in the program?
941 ///
942 /// The response is really only definitive when called at the end of
943 /// the translation unit.
944 ///
945 /// The only semantic restriction here is that the object file should
946 /// not contain a vtable definition when that vtable is defined
947 /// strongly elsewhere. Otherwise, we'd just like to avoid emitting
948 /// vtables when unnecessary.
950  assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
951 
952  // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
953  // emit them even if there is an explicit template instantiation.
954  if (CGM.getTarget().getCXXABI().isMicrosoft())
955  return false;
956 
957  // If we have an explicit instantiation declaration (and not a
958  // definition), the vtable is defined elsewhere.
961  return true;
962 
963  // Otherwise, if the class is an instantiated template, the
964  // vtable must be defined here.
965  if (TSK == TSK_ImplicitInstantiation ||
967  return false;
968 
969  // Otherwise, if the class doesn't have a key function (possibly
970  // anymore), the vtable must be defined here.
971  const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
972  if (!keyFunction)
973  return false;
974 
975  // Otherwise, if we don't have a definition of the key function, the
976  // vtable must be defined somewhere else.
977  return !keyFunction->hasBody();
978 }
979 
980 /// Given that we're currently at the end of the translation unit, and
981 /// we've emitted a reference to the vtable for this class, should
982 /// we define that vtable?
984  const CXXRecordDecl *RD) {
985  // If vtable is internal then it has to be done.
986  if (!CGM.getVTables().isVTableExternal(RD))
987  return true;
988 
989  // If it's external then maybe we will need it as available_externally.
990  return shouldEmitAvailableExternallyVTable(CGM, RD);
991 }
992 
993 /// Given that at some point we emitted a reference to one or more
994 /// vtables, and that we are now at the end of the translation unit,
995 /// decide whether we should emit them.
996 void CodeGenModule::EmitDeferredVTables() {
997 #ifndef NDEBUG
998  // Remember the size of DeferredVTables, because we're going to assume
999  // that this entire operation doesn't modify it.
1000  size_t savedSize = DeferredVTables.size();
1001 #endif
1002 
1003  for (const CXXRecordDecl *RD : DeferredVTables)
1005  VTables.GenerateClassData(RD);
1006  else if (shouldOpportunisticallyEmitVTables())
1007  OpportunisticVTables.push_back(RD);
1008 
1009  assert(savedSize == DeferredVTables.size() &&
1010  "deferred extra vtables during vtable emission?");
1011  DeferredVTables.clear();
1012 }
1013 
1016  if (!isExternallyVisible(LV.getLinkage()))
1017  return true;
1018 
1019  if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
1020  return false;
1021 
1022  if (getTriple().isOSBinFormatCOFF()) {
1023  if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
1024  return false;
1025  } else {
1026  if (LV.getVisibility() != HiddenVisibility)
1027  return false;
1028  }
1029 
1030  if (getCodeGenOpts().LTOVisibilityPublicStd) {
1031  const DeclContext *DC = RD;
1032  while (1) {
1033  auto *D = cast<Decl>(DC);
1034  DC = DC->getParent();
1035  if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
1036  if (auto *ND = dyn_cast<NamespaceDecl>(D))
1037  if (const IdentifierInfo *II = ND->getIdentifier())
1038  if (II->isStr("std") || II->isStr("stdext"))
1039  return false;
1040  break;
1041  }
1042  }
1043  }
1044 
1045  return true;
1046 }
1047 
1048 llvm::GlobalObject::VCallVisibility
1051  llvm::GlobalObject::VCallVisibility TypeVis;
1052  if (!isExternallyVisible(LV.getLinkage()))
1053  TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1054  else if (HasHiddenLTOVisibility(RD))
1055  TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1056  else
1057  TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1058 
1059  for (auto B : RD->bases())
1060  if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1061  TypeVis = std::min(TypeVis,
1062  GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl()));
1063 
1064  for (auto B : RD->vbases())
1065  if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1066  TypeVis = std::min(TypeVis,
1067  GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl()));
1068 
1069  return TypeVis;
1070 }
1071 
1073  llvm::GlobalVariable *VTable,
1074  const VTableLayout &VTLayout) {
1075  if (!getCodeGenOpts().LTOUnit)
1076  return;
1077 
1078  CharUnits PointerWidth =
1079  Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1080 
1081  typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
1082  std::vector<AddressPoint> AddressPoints;
1083  for (auto &&AP : VTLayout.getAddressPoints())
1084  AddressPoints.push_back(std::make_pair(
1085  AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
1086  AP.second.AddressPointIndex));
1087 
1088  // Sort the address points for determinism.
1089  llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
1090  const AddressPoint &AP2) {
1091  if (&AP1 == &AP2)
1092  return false;
1093 
1094  std::string S1;
1095  llvm::raw_string_ostream O1(S1);
1096  getCXXABI().getMangleContext().mangleTypeName(
1097  QualType(AP1.first->getTypeForDecl(), 0), O1);
1098  O1.flush();
1099 
1100  std::string S2;
1101  llvm::raw_string_ostream O2(S2);
1102  getCXXABI().getMangleContext().mangleTypeName(
1103  QualType(AP2.first->getTypeForDecl(), 0), O2);
1104  O2.flush();
1105 
1106  if (S1 < S2)
1107  return true;
1108  if (S1 != S2)
1109  return false;
1110 
1111  return AP1.second < AP2.second;
1112  });
1113 
1114  ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1115  for (auto AP : AddressPoints) {
1116  // Create type metadata for the address point.
1117  AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
1118 
1119  // The class associated with each address point could also potentially be
1120  // used for indirect calls via a member function pointer, so we need to
1121  // annotate the address of each function pointer with the appropriate member
1122  // function pointer type.
1123  for (unsigned I = 0; I != Comps.size(); ++I) {
1124  if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1125  continue;
1126  llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1127  Context.getMemberPointerType(
1128  Comps[I].getFunctionDecl()->getType(),
1129  Context.getRecordType(AP.first).getTypePtr()));
1130  VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
1131  }
1132  }
1133 
1134  if (getCodeGenOpts().VirtualFunctionElimination) {
1135  llvm::GlobalObject::VCallVisibility TypeVis = GetVCallVisibilityLevel(RD);
1136  if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1137  VTable->addVCallVisibilityMetadata(TypeVis);
1138  }
1139 }
const llvm::DataLayout & getDataLayout() const
size_t getNumVTables() const
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:359
static const Decl * getCanonicalDecl(const Decl *D)
Represents a function declaration or definition.
Definition: Decl.h:1783
External linkage, which indicates that the entity can be referred to from other translation units...
Definition: Linkage.h:59
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F)
Set the LLVM function attributes (sext, zext, etc).
CanQualType VoidPtrTy
Definition: ASTContext.h:1044
A (possibly-)qualified type.
Definition: Type.h:654
bool ReturnTypeUsesSRet(const CGFunctionInfo &FI)
Return true iff the given type uses &#39;sret&#39; when used as a return type.
Definition: CGCall.cpp:1512
base_class_range bases()
Definition: DeclCXX.h:587
const CodeGenOptions & getCodeGenOpts() const
const AddressPointsMapTy & getAddressPoints() const
virtual void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResultType)
Definition: CGCXXABI.cpp:157
llvm::LLVMContext & getLLVMContext()
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:84
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:37
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3422
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:557
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:602
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2352
bool isEmpty() const
Definition: ABI.h:86
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:707
llvm::Function * GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk)
Definition: CGVTables.cpp:157
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:1014
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:2883
void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo, bool IsUnprototyped)
Definition: CGVTables.cpp:236
bool ReturnValue(const T &V, APValue &R)
Convers a value to an APValue.
Definition: Interp.h:41
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:36
Visibility getVisibility() const
Definition: Visibility.h:84
CGDebugInfo * getModuleDebugInfo()
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:54
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
llvm::Value * getPointer() const
Definition: Address.h:37
Don&#39;t generate debug info.
Represents a parameter to a function.
Definition: Decl.h:1595
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:23
void add(RValue rvalue, QualType type)
Definition: CGCall.h:285
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:361
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:1063
void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, GlobalDecl GD, const ThunkInfo &Thunk, bool IsUnprototyped)
Generate a thunk for the given method.
Definition: CGVTables.cpp:443
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:822
bool isReferenceType() const
Definition: Type.h:6516
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:118
llvm::Type * getVTableType(const VTableLayout &layout)
Returns the type of a vtable with the given layout.
Definition: CGVTables.cpp:736
The this pointer adjustment as well as an optional return adjustment for a thunk. ...
Definition: ABI.h:178
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:769
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2399
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
ArrayRef< VTableComponent > vtable_components() const
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:34
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
Definition: CGCXXABI.h:108
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6326
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:1836
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr or CxxCtorInitializer) selects the name&#39;s to...
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
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...
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6256
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:78
static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD, bool IsUnprototyped, bool ForVTable)
Definition: CGVTables.cpp:470
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:513
param_iterator param_begin()
Definition: Decl.h:2411
bool hasAttr() const
Definition: DeclBase.h:542
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1690
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3754
bool isDynamicClass() const
Definition: DeclCXX.h:553
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:1700
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:949
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:106
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:235
static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk, llvm::Function *ThunkFn, bool ForVTable, GlobalDecl GD)
Definition: CGVTables.cpp:40
static bool similar(const ABIArgInfo &infoL, CanQualType typeL, const ABIArgInfo &infoR, CanQualType typeR)
Definition: CGVTables.cpp:60
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7067
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:133
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2649
virtual bool exportThunk()=0
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:83
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: Decl.cpp:2859
Base object dtor.
Definition: ABI.h:36
const CGFunctionInfo & arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD)
Arrange a thunk that takes &#39;this&#39; as the first parameter followed by varargs.
Definition: CGCall.cpp:530
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1784
void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee, const ThunkInfo *Thunk, bool IsUnprototyped)
Definition: CGVTables.cpp:292
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:91
QualType getRecordType(const RecordDecl *Decl) const
const TargetInfo & getTarget() const
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:181
const LangOptions & getLangOpts() const
ASTContext & getContext() const
virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, CallArgList &CallArgs)
Definition: CGCXXABI.h:434
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:265
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:40
The l-value was considered opaque, so the alignment was determined from a type.
ArrayRef< VTableThunkTy > vtable_thunks() const
virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, const ThisAdjustment &ThisAdjustment, raw_ostream &)=0
llvm::Constant * GetAddrOfThunk(StringRef Name, llvm::Type *FnTy, GlobalDecl GD)
Get the address of the thunk for the given global decl.
Definition: CGVTables.cpp:34
Encodes a location in the source.
QualType getReturnType() const
Definition: Type.h:3680
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
const Decl * getDecl() const
Definition: GlobalDecl.h:77
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:43
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1931
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
CanQualType VoidTy
Definition: ASTContext.h:1016
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:745
An aligned address.
Definition: Address.h:24
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.
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:96
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:193
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:178
Complete object dtor.
Definition: ABI.h:35
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:761
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:355
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:180
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3756
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:189
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2046
void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params)
Build a parameter variable suitable for &#39;this&#39;.
Definition: CGCXXABI.cpp:122
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name. ...
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:175
llvm::Module & getModule() const
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
Definition: CGVTables.cpp:601
param_iterator param_end()
Definition: Decl.h:2412
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:832
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
void EmitVTableTypeMetadata(const CXXRecordDecl *RD, llvm::GlobalVariable *VTable, const VTableLayout &VTLayout)
Emit type metadata for the given vtable using the given layout.
Definition: CGVTables.cpp:1072
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
Definition: Decl.cpp:1098
StructBuilder beginStruct(llvm::StructType *structTy=nullptr)
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:185
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:983
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
Definition: CGVTables.cpp:929
ReturnAdjustment Return
The return adjustment.
Definition: ABI.h:183
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:31
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:473
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2513
llvm::Type * GetFunctionTypeForVTable(GlobalDecl GD)
GetFunctionTypeForVTable - Get the LLVM function type for use in a vtable, given a CXXMethodDecl...
Definition: CGCall.cpp:1684
llvm::GlobalObject::VCallVisibility GetVCallVisibilityLevel(const CXXRecordDecl *RD)
Returns the vcall visibility of the given type.
Definition: CGVTables.cpp:1049
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
static RValue PerformReturnAdjustment(CodeGenFunction &CGF, QualType ResultType, RValue RV, const ThunkInfo &Thunk)
Definition: CGVTables.cpp:69
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:253
bool isVoidType() const
Definition: Type.h:6777
virtual void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, raw_ostream &)=0
A helper class of ConstantInitBuilder, used for building constant struct initializers.
size_t getVTableSize(size_t i) const
__DEVICE__ int min(int __a, int __b)
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:160
A pointer to the deleting destructor.
Definition: VTableBuilder.h:42
CGCXXABI & getCXXABI() const
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, unsigned Alignment)
Will return a global variable of the given type.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:947
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
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:786
QualType getType() const
Definition: Decl.h:630
CodeGenVTables & getVTables()
void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, llvm::FunctionCallee Callee)
Emit a musttail call for a thunk with a potentially adjusted this pointer.
Definition: CGVTables.cpp:390
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:261
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:675
const LangOptions & getLangOpts() const
Definition: ASTContext.h:724
base_class_range vbases()
Definition: DeclCXX.h:604
A pointer to the complete destructor.
Definition: VTableBuilder.h:39
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:429
bool isExternallyVisible() const
Definition: Decl.h:362
void EmitVTable(CXXRecordDecl *Class)
This is a callback from Sema to tell us that a particular vtable is required to be emitted in this tr...
Definition: CGVTables.cpp:924
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1556
const llvm::Triple & getTriple() const