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 "CodeGenModule.h"
15 #include "CodeGenFunction.h"
16 #include "CGCXXABI.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/Frontend/CodeGenOptions.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/Support/Compiler.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 
31 CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32   : CGM(CGM), VTContext(CGM.getContext()) { }
33 
34 bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
35   assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
36 
37   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
38   if (TSK == TSK_ExplicitInstantiationDeclaration)
39     return false;
40 
41   const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
42   if (!KeyFunction)
43     return true;
44 
45   // Itanium C++ ABI, 5.2.6 Instantiated Templates:
46   //    An instantiation of a class template requires:
47   //        - In the object where instantiated, the virtual table...
48   if (TSK == TSK_ImplicitInstantiation ||
49       TSK == TSK_ExplicitInstantiationDefinition)
50     return true;
51 
52   // If we're building with optimization, we always emit VTables since that
53   // allows for virtual function calls to be devirtualized.
54   // (We don't want to do this in -fapple-kext mode however).
55   if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOpts().AppleKext)
56     return true;
57 
58   return KeyFunction->hasBody();
59 }
60 
61 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
62                                               const ThunkInfo &Thunk) {
63   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
64 
65   // Compute the mangled name.
66   SmallString<256> Name;
67   llvm::raw_svector_ostream Out(Name);
68   if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
69     getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
70                                                       Thunk.This, Out);
71   else
72     getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
73   Out.flush();
74 
75   llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
76   return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
77 }
78 
79 static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
80                                           llvm::Value *Ptr,
81                                           int64_t NonVirtualAdjustment,
82                                           int64_t VirtualAdjustment,
83                                           bool IsReturnAdjustment) {
84   if (!NonVirtualAdjustment && !VirtualAdjustment)
85     return Ptr;
86 
87   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
88   llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
89 
90   if (NonVirtualAdjustment && !IsReturnAdjustment) {
91     // Perform the non-virtual adjustment for a base-to-derived cast.
92     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
93   }
94 
95   if (VirtualAdjustment) {
96     llvm::Type *PtrDiffTy =
97       CGF.ConvertType(CGF.getContext().getPointerDiffType());
98 
99     // Perform the virtual adjustment.
100     llvm::Value *VTablePtrPtr =
101       CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
102 
103     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
104 
105     llvm::Value *OffsetPtr =
106       CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
107 
108     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
109 
110     // Load the adjustment offset from the vtable.
111     llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
112 
113     // Adjust our pointer.
114     V = CGF.Builder.CreateInBoundsGEP(V, Offset);
115   }
116 
117   if (NonVirtualAdjustment && IsReturnAdjustment) {
118     // Perform the non-virtual adjustment for a derived-to-base cast.
119     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
120   }
121 
122   // Cast back to the original type.
123   return CGF.Builder.CreateBitCast(V, Ptr->getType());
124 }
125 
126 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
127                                const ThunkInfo &Thunk, llvm::Function *Fn) {
128   CGM.setGlobalVisibility(Fn, MD);
129 
130   if (!CGM.getCodeGenOpts().HiddenWeakVTables)
131     return;
132 
133   // If the thunk has weak/linkonce linkage, but the function must be
134   // emitted in every translation unit that references it, then we can
135   // emit its thunks with hidden visibility, since its thunks must be
136   // emitted when the function is.
137 
138   // This follows CodeGenModule::setTypeVisibility; see the comments
139   // there for explanation.
140 
141   if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
142        Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
143       Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
144     return;
145 
146   if (MD->getExplicitVisibility())
147     return;
148 
149   switch (MD->getTemplateSpecializationKind()) {
150   case TSK_ExplicitInstantiationDefinition:
151   case TSK_ExplicitInstantiationDeclaration:
152     return;
153 
154   case TSK_Undeclared:
155     break;
156 
157   case TSK_ExplicitSpecialization:
158   case TSK_ImplicitInstantiation:
159     if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
160       return;
161     break;
162   }
163 
164   // If there's an explicit definition, and that definition is
165   // out-of-line, then we can't assume that all users will have a
166   // definition to emit.
167   const FunctionDecl *Def = 0;
168   if (MD->hasBody(Def) && Def->isOutOfLine())
169     return;
170 
171   Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
172 }
173 
174 #ifndef NDEBUG
175 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
176                     const ABIArgInfo &infoR, CanQualType typeR) {
177   return (infoL.getKind() == infoR.getKind() &&
178           (typeL == typeR ||
179            (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
180            (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
181 }
182 #endif
183 
184 static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
185                                       QualType ResultType, RValue RV,
186                                       const ThunkInfo &Thunk) {
187   // Emit the return adjustment.
188   bool NullCheckValue = !ResultType->isReferenceType();
189 
190   llvm::BasicBlock *AdjustNull = 0;
191   llvm::BasicBlock *AdjustNotNull = 0;
192   llvm::BasicBlock *AdjustEnd = 0;
193 
194   llvm::Value *ReturnValue = RV.getScalarVal();
195 
196   if (NullCheckValue) {
197     AdjustNull = CGF.createBasicBlock("adjust.null");
198     AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
199     AdjustEnd = CGF.createBasicBlock("adjust.end");
200 
201     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
202     CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
203     CGF.EmitBlock(AdjustNotNull);
204   }
205 
206   ReturnValue = PerformTypeAdjustment(CGF, ReturnValue,
207                                       Thunk.Return.NonVirtual,
208                                       Thunk.Return.VBaseOffsetOffset,
209                                       /*IsReturnAdjustment*/true);
210 
211   if (NullCheckValue) {
212     CGF.Builder.CreateBr(AdjustEnd);
213     CGF.EmitBlock(AdjustNull);
214     CGF.Builder.CreateBr(AdjustEnd);
215     CGF.EmitBlock(AdjustEnd);
216 
217     llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
218     PHI->addIncoming(ReturnValue, AdjustNotNull);
219     PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
220                      AdjustNull);
221     ReturnValue = PHI;
222   }
223 
224   return RValue::get(ReturnValue);
225 }
226 
227 // This function does roughly the same thing as GenerateThunk, but in a
228 // very different way, so that va_start and va_end work correctly.
229 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
230 //        a function, and that there is an alloca built in the entry block
231 //        for all accesses to "this".
232 // FIXME: This function assumes there is only one "ret" statement per function.
233 // FIXME: Cloning isn't correct in the presence of indirect goto!
234 // FIXME: This implementation of thunks bloats codesize by duplicating the
235 //        function definition.  There are alternatives:
236 //        1. Add some sort of stub support to LLVM for cases where we can
237 //           do a this adjustment, then a sibcall.
238 //        2. We could transform the definition to take a va_list instead of an
239 //           actual variable argument list, then have the thunks (including a
240 //           no-op thunk for the regular definition) call va_start/va_end.
241 //           There's a bit of per-call overhead for this solution, but it's
242 //           better for codesize if the definition is long.
243 void CodeGenFunction::GenerateVarArgsThunk(
244                                       llvm::Function *Fn,
245                                       const CGFunctionInfo &FnInfo,
246                                       GlobalDecl GD, const ThunkInfo &Thunk) {
247   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
248   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
249   QualType ResultType = FPT->getResultType();
250 
251   // Get the original function
252   assert(FnInfo.isVariadic());
253   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
254   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
255   llvm::Function *BaseFn = cast<llvm::Function>(Callee);
256 
257   // Clone to thunk.
258   llvm::Function *NewFn = llvm::CloneFunction(BaseFn);
259   CGM.getModule().getFunctionList().push_back(NewFn);
260   Fn->replaceAllUsesWith(NewFn);
261   NewFn->takeName(Fn);
262   Fn->eraseFromParent();
263   Fn = NewFn;
264 
265   // "Initialize" CGF (minimally).
266   CurFn = Fn;
267 
268   // Get the "this" value
269   llvm::Function::arg_iterator AI = Fn->arg_begin();
270   if (CGM.ReturnTypeUsesSRet(FnInfo))
271     ++AI;
272 
273   // Find the first store of "this", which will be to the alloca associated
274   // with "this".
275   llvm::Value *ThisPtr = &*AI;
276   llvm::BasicBlock *EntryBB = Fn->begin();
277   llvm::Instruction *ThisStore = 0;
278   for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
279        I != E; I++) {
280     if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
281       ThisStore = cast<llvm::StoreInst>(I);
282       break;
283     }
284   }
285   assert(ThisStore && "Store of this should be in entry block?");
286   // Adjust "this", if necessary.
287   Builder.SetInsertPoint(ThisStore);
288   llvm::Value *AdjustedThisPtr =
289     PerformTypeAdjustment(*this, ThisPtr,
290                           Thunk.This.NonVirtual,
291                           Thunk.This.VCallOffsetOffset,
292                           /*IsReturnAdjustment*/false);
293   ThisStore->setOperand(0, AdjustedThisPtr);
294 
295   if (!Thunk.Return.isEmpty()) {
296     // Fix up the returned value, if necessary.
297     for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
298       llvm::Instruction *T = I->getTerminator();
299       if (isa<llvm::ReturnInst>(T)) {
300         RValue RV = RValue::get(T->getOperand(0));
301         T->eraseFromParent();
302         Builder.SetInsertPoint(&*I);
303         RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
304         Builder.CreateRet(RV.getScalarVal());
305         break;
306       }
307     }
308   }
309 }
310 
311 void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
312                                     const CGFunctionInfo &FnInfo,
313                                     GlobalDecl GD, const ThunkInfo &Thunk) {
314   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
315   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
316   QualType ResultType = FPT->getResultType();
317   QualType ThisType = MD->getThisType(getContext());
318 
319   FunctionArgList FunctionArgs;
320 
321   // FIXME: It would be nice if more of this code could be shared with
322   // CodeGenFunction::GenerateCode.
323 
324   // Create the implicit 'this' parameter declaration.
325   CurGD = GD;
326   CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
327 
328   // Add the rest of the parameters.
329   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
330        E = MD->param_end(); I != E; ++I) {
331     ParmVarDecl *Param = *I;
332 
333     FunctionArgs.push_back(Param);
334   }
335 
336   StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
337                 SourceLocation());
338 
339   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
340   CXXThisValue = CXXABIThisValue;
341 
342   // Adjust the 'this' pointer if necessary.
343   llvm::Value *AdjustedThisPtr =
344     PerformTypeAdjustment(*this, LoadCXXThis(),
345                           Thunk.This.NonVirtual,
346                           Thunk.This.VCallOffsetOffset,
347                           /*IsReturnAdjustment*/false);
348 
349   CallArgList CallArgs;
350 
351   // Add our adjusted 'this' pointer.
352   CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
353 
354   // Add the rest of the parameters.
355   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
356        E = MD->param_end(); I != E; ++I) {
357     ParmVarDecl *param = *I;
358     EmitDelegateCallArg(CallArgs, param);
359   }
360 
361   // Get our callee.
362   llvm::Type *Ty =
363     CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
364   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
365 
366 #ifndef NDEBUG
367   const CGFunctionInfo &CallFnInfo =
368     CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
369                                        RequiredArgs::forPrototypePlus(FPT, 1));
370   assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
371          CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
372          CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
373   assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
374          similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
375                  FnInfo.getReturnInfo(), FnInfo.getReturnType()));
376   assert(CallFnInfo.arg_size() == FnInfo.arg_size());
377   for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
378     assert(similar(CallFnInfo.arg_begin()[i].info,
379                    CallFnInfo.arg_begin()[i].type,
380                    FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
381 #endif
382 
383   // Determine whether we have a return value slot to use.
384   ReturnValueSlot Slot;
385   if (!ResultType->isVoidType() &&
386       FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
387       hasAggregateLLVMType(CurFnInfo->getReturnType()))
388     Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
389 
390   // Now emit our call.
391   RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
392 
393   if (!Thunk.Return.isEmpty())
394     RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
395 
396   if (!ResultType->isVoidType() && Slot.isNull())
397     CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
398 
399   // Disable the final ARC autorelease.
400   AutoreleaseResult = false;
401 
402   FinishFunction();
403 
404   // Set the right linkage.
405   CGM.setFunctionLinkage(MD, Fn);
406 
407   // Set the right visibility.
408   setThunkVisibility(CGM, MD, Thunk, Fn);
409 }
410 
411 void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
412                                bool UseAvailableExternallyLinkage)
413 {
414   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
415 
416   // FIXME: re-use FnInfo in this computation.
417   llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
418 
419   // Strip off a bitcast if we got one back.
420   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
421     assert(CE->getOpcode() == llvm::Instruction::BitCast);
422     Entry = CE->getOperand(0);
423   }
424 
425   // There's already a declaration with the same name, check if it has the same
426   // type or if we need to replace it.
427   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
428       CGM.getTypes().GetFunctionTypeForVTable(GD)) {
429     llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
430 
431     // If the types mismatch then we have to rewrite the definition.
432     assert(OldThunkFn->isDeclaration() &&
433            "Shouldn't replace non-declaration");
434 
435     // Remove the name from the old thunk function and get a new thunk.
436     OldThunkFn->setName(StringRef());
437     Entry = CGM.GetAddrOfThunk(GD, Thunk);
438 
439     // If needed, replace the old thunk with a bitcast.
440     if (!OldThunkFn->use_empty()) {
441       llvm::Constant *NewPtrForOldDecl =
442         llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
443       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
444     }
445 
446     // Remove the old thunk.
447     OldThunkFn->eraseFromParent();
448   }
449 
450   llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
451 
452   if (!ThunkFn->isDeclaration()) {
453     if (UseAvailableExternallyLinkage) {
454       // There is already a thunk emitted for this function, do nothing.
455       return;
456     }
457 
458     // If a function has a body, it should have available_externally linkage.
459     assert(ThunkFn->hasAvailableExternallyLinkage() &&
460            "Function should have available_externally linkage!");
461 
462     // Change the linkage.
463     CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn);
464     return;
465   }
466 
467   if (ThunkFn->isVarArg()) {
468     // Varargs thunks are special; we can't just generate a call because
469     // we can't copy the varargs.  Our implementation is rather
470     // expensive/sucky at the moment, so don't generate the thunk unless
471     // we have to.
472     // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
473     if (!UseAvailableExternallyLinkage)
474       CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
475   } else {
476     // Normal thunk body generation.
477     CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
478   }
479 
480   if (UseAvailableExternallyLinkage)
481     ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
482 }
483 
484 void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
485                                                        const ThunkInfo &Thunk) {
486   // We only want to do this when building with optimizations.
487   if (!CGM.getCodeGenOpts().OptimizationLevel)
488     return;
489 
490   // We can't emit thunks for member functions with incomplete types.
491   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
492   if (!CGM.getTypes().isFuncTypeConvertible(
493                                 cast<FunctionType>(MD->getType().getTypePtr())))
494     return;
495 
496   EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
497 }
498 
499 void CodeGenVTables::EmitThunks(GlobalDecl GD)
500 {
501   const CXXMethodDecl *MD =
502     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
503 
504   // We don't need to generate thunks for the base destructor.
505   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
506     return;
507 
508   const VTableContext::ThunkInfoVectorTy *ThunkInfoVector =
509     VTContext.getThunkInfo(MD);
510   if (!ThunkInfoVector)
511     return;
512 
513   for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
514     EmitThunk(GD, (*ThunkInfoVector)[I],
515               /*UseAvailableExternallyLinkage=*/false);
516 }
517 
518 llvm::Constant *
519 CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
520                                         const VTableComponent *Components,
521                                         unsigned NumComponents,
522                                 const VTableLayout::VTableThunkTy *VTableThunks,
523                                         unsigned NumVTableThunks) {
524   SmallVector<llvm::Constant *, 64> Inits;
525 
526   llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
527 
528   llvm::Type *PtrDiffTy =
529     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
530 
531   QualType ClassType = CGM.getContext().getTagDeclType(RD);
532   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
533 
534   unsigned NextVTableThunkIndex = 0;
535 
536   llvm::Constant* PureVirtualFn = 0;
537 
538   for (unsigned I = 0; I != NumComponents; ++I) {
539     VTableComponent Component = Components[I];
540 
541     llvm::Constant *Init = 0;
542 
543     switch (Component.getKind()) {
544     case VTableComponent::CK_VCallOffset:
545       Init = llvm::ConstantInt::get(PtrDiffTy,
546                                     Component.getVCallOffset().getQuantity());
547       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
548       break;
549     case VTableComponent::CK_VBaseOffset:
550       Init = llvm::ConstantInt::get(PtrDiffTy,
551                                     Component.getVBaseOffset().getQuantity());
552       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
553       break;
554     case VTableComponent::CK_OffsetToTop:
555       Init = llvm::ConstantInt::get(PtrDiffTy,
556                                     Component.getOffsetToTop().getQuantity());
557       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
558       break;
559     case VTableComponent::CK_RTTI:
560       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
561       break;
562     case VTableComponent::CK_FunctionPointer:
563     case VTableComponent::CK_CompleteDtorPointer:
564     case VTableComponent::CK_DeletingDtorPointer: {
565       GlobalDecl GD;
566 
567       // Get the right global decl.
568       switch (Component.getKind()) {
569       default:
570         llvm_unreachable("Unexpected vtable component kind");
571       case VTableComponent::CK_FunctionPointer:
572         GD = Component.getFunctionDecl();
573         break;
574       case VTableComponent::CK_CompleteDtorPointer:
575         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
576         break;
577       case VTableComponent::CK_DeletingDtorPointer:
578         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
579         break;
580       }
581 
582       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
583         // We have a pure virtual member function.
584         if (!PureVirtualFn) {
585           llvm::FunctionType *Ty =
586             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
587           StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
588           PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
589           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
590                                                          CGM.Int8PtrTy);
591         }
592         Init = PureVirtualFn;
593       } else {
594         // Check if we should use a thunk.
595         if (NextVTableThunkIndex < NumVTableThunks &&
596             VTableThunks[NextVTableThunkIndex].first == I) {
597           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
598 
599           MaybeEmitThunkAvailableExternally(GD, Thunk);
600           Init = CGM.GetAddrOfThunk(GD, Thunk);
601 
602           NextVTableThunkIndex++;
603         } else {
604           llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
605 
606           Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
607         }
608 
609         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
610       }
611       break;
612     }
613 
614     case VTableComponent::CK_UnusedFunctionPointer:
615       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
616       break;
617     };
618 
619     Inits.push_back(Init);
620   }
621 
622   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
623   return llvm::ConstantArray::get(ArrayType, Inits);
624 }
625 
626 llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
627   llvm::GlobalVariable *&VTable = VTables[RD];
628   if (VTable)
629     return VTable;
630 
631   // We may need to generate a definition for this vtable.
632   if (ShouldEmitVTableInThisTU(RD))
633     CGM.DeferredVTables.push_back(RD);
634 
635   SmallString<256> OutName;
636   llvm::raw_svector_ostream Out(OutName);
637   CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
638   Out.flush();
639   StringRef Name = OutName.str();
640 
641   llvm::ArrayType *ArrayType =
642     llvm::ArrayType::get(CGM.Int8PtrTy,
643                         VTContext.getVTableLayout(RD).getNumVTableComponents());
644 
645   VTable =
646     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
647                                           llvm::GlobalValue::ExternalLinkage);
648   VTable->setUnnamedAddr(true);
649   return VTable;
650 }
651 
652 void
653 CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
654                                      llvm::GlobalVariable::LinkageTypes Linkage,
655                                      const CXXRecordDecl *RD) {
656   const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
657 
658   // Create and set the initializer.
659   llvm::Constant *Init =
660     CreateVTableInitializer(RD,
661                             VTLayout.vtable_component_begin(),
662                             VTLayout.getNumVTableComponents(),
663                             VTLayout.vtable_thunk_begin(),
664                             VTLayout.getNumVTableThunks());
665   VTable->setInitializer(Init);
666 
667   // Set the correct linkage.
668   VTable->setLinkage(Linkage);
669 
670   // Set the right visibility.
671   CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
672 }
673 
674 llvm::GlobalVariable *
675 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
676                                       const BaseSubobject &Base,
677                                       bool BaseIsVirtual,
678                                    llvm::GlobalVariable::LinkageTypes Linkage,
679                                       VTableAddressPointsMapTy& AddressPoints) {
680   OwningPtr<VTableLayout> VTLayout(
681     VTContext.createConstructionVTableLayout(Base.getBase(),
682                                              Base.getBaseOffset(),
683                                              BaseIsVirtual, RD));
684 
685   // Add the address points.
686   AddressPoints = VTLayout->getAddressPoints();
687 
688   // Get the mangled construction vtable name.
689   SmallString<256> OutName;
690   llvm::raw_svector_ostream Out(OutName);
691   CGM.getCXXABI().getMangleContext().
692     mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
693                         Out);
694   Out.flush();
695   StringRef Name = OutName.str();
696 
697   llvm::ArrayType *ArrayType =
698     llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
699 
700   // Create the variable that will hold the construction vtable.
701   llvm::GlobalVariable *VTable =
702     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
703   CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
704 
705   // V-tables are always unnamed_addr.
706   VTable->setUnnamedAddr(true);
707 
708   // Create and set the initializer.
709   llvm::Constant *Init =
710     CreateVTableInitializer(Base.getBase(),
711                             VTLayout->vtable_component_begin(),
712                             VTLayout->getNumVTableComponents(),
713                             VTLayout->vtable_thunk_begin(),
714                             VTLayout->getNumVTableThunks());
715   VTable->setInitializer(Init);
716 
717   return VTable;
718 }
719 
720 void
721 CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
722                                   const CXXRecordDecl *RD) {
723   llvm::GlobalVariable *VTable = GetAddrOfVTable(RD);
724   if (VTable->hasInitializer())
725     return;
726 
727   EmitVTableDefinition(VTable, Linkage, RD);
728 
729   if (RD->getNumVBases()) {
730     llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
731     EmitVTTDefinition(VTT, Linkage, RD);
732   }
733 
734   // If this is the magic class __cxxabiv1::__fundamental_type_info,
735   // we will emit the typeinfo for the fundamental types. This is the
736   // same behaviour as GCC.
737   const DeclContext *DC = RD->getDeclContext();
738   if (RD->getIdentifier() &&
739       RD->getIdentifier()->isStr("__fundamental_type_info") &&
740       isa<NamespaceDecl>(DC) &&
741       cast<NamespaceDecl>(DC)->getIdentifier() &&
742       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
743       DC->getParent()->isTranslationUnit())
744     CGM.EmitFundamentalRTTIDescriptors();
745 }
746