1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
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 provides C++ code generation targeting the Microsoft Visual C++ ABI.
11 // The class in this file generates structures that follow the Microsoft
12 // Visual C++ ABI, which is actually not very well documented at all outside
13 // of Microsoft.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CGCXXABI.h"
18 #include "CGVTables.h"
19 #include "CodeGenModule.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/VTableBuilder.h"
23 #include "llvm/ADT/StringSet.h"
24 
25 using namespace clang;
26 using namespace CodeGen;
27 
28 namespace {
29 
30 /// Holds all the vbtable globals for a given class.
31 struct VBTableGlobals {
32   const VBTableVector *VBTables;
33   SmallVector<llvm::GlobalVariable *, 2> Globals;
34 };
35 
36 class MicrosoftCXXABI : public CGCXXABI {
37 public:
38   MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
39 
40   bool HasThisReturn(GlobalDecl GD) const;
41 
42   bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
43     // Structures that are not C++03 PODs are always indirect.
44     return !RD->isPOD();
45   }
46 
47   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
48     if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
49       return RAA_DirectInMemory;
50     return RAA_Default;
51   }
52 
53   StringRef GetPureVirtualCallName() { return "_purecall"; }
54   // No known support for deleted functions in MSVC yet, so this choice is
55   // arbitrary.
56   StringRef GetDeletedVirtualCallName() { return "_purecall"; }
57 
58   bool isInlineInitializedStaticDataMemberLinkOnce() { return true; }
59 
60   llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
61                                       llvm::Value *ptr,
62                                       QualType type);
63 
64   llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
65                                          llvm::Value *This,
66                                          const CXXRecordDecl *ClassDecl,
67                                          const CXXRecordDecl *BaseClassDecl);
68 
69   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
70                                  CXXCtorType Type,
71                                  CanQualType &ResTy,
72                                  SmallVectorImpl<CanQualType> &ArgTys);
73 
74   llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
75                                                   const CXXRecordDecl *RD);
76 
77   void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
78                                                  const CXXRecordDecl *RD);
79 
80   void EmitCXXConstructors(const CXXConstructorDecl *D);
81 
82   // Background on MSVC destructors
83   // ==============================
84   //
85   // Both Itanium and MSVC ABIs have destructor variants.  The variant names
86   // roughly correspond in the following way:
87   //   Itanium       Microsoft
88   //   Base       -> no name, just ~Class
89   //   Complete   -> vbase destructor
90   //   Deleting   -> scalar deleting destructor
91   //                 vector deleting destructor
92   //
93   // The base and complete destructors are the same as in Itanium, although the
94   // complete destructor does not accept a VTT parameter when there are virtual
95   // bases.  A separate mechanism involving vtordisps is used to ensure that
96   // virtual methods of destroyed subobjects are not called.
97   //
98   // The deleting destructors accept an i32 bitfield as a second parameter.  Bit
99   // 1 indicates if the memory should be deleted.  Bit 2 indicates if the this
100   // pointer points to an array.  The scalar deleting destructor assumes that
101   // bit 2 is zero, and therefore does not contain a loop.
102   //
103   // For virtual destructors, only one entry is reserved in the vftable, and it
104   // always points to the vector deleting destructor.  The vector deleting
105   // destructor is the most general, so it can be used to destroy objects in
106   // place, delete single heap objects, or delete arrays.
107   //
108   // A TU defining a non-inline destructor is only guaranteed to emit a base
109   // destructor, and all of the other variants are emitted on an as-needed basis
110   // in COMDATs.  Because a non-base destructor can be emitted in a TU that
111   // lacks a definition for the destructor, non-base destructors must always
112   // delegate to or alias the base destructor.
113 
114   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
115                                 CXXDtorType Type,
116                                 CanQualType &ResTy,
117                                 SmallVectorImpl<CanQualType> &ArgTys);
118 
119   /// Non-base dtors should be emitted as delegating thunks in this ABI.
120   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
121                               CXXDtorType DT) const {
122     return DT != Dtor_Base;
123   }
124 
125   void EmitCXXDestructors(const CXXDestructorDecl *D);
126 
127   const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
128     MD = MD->getCanonicalDecl();
129     if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
130       MicrosoftVTableContext::MethodVFTableLocation ML =
131           CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
132       // The vbases might be ordered differently in the final overrider object
133       // and the complete object, so the "this" argument may sometimes point to
134       // memory that has no particular type (e.g. past the complete object).
135       // In this case, we just use a generic pointer type.
136       // FIXME: might want to have a more precise type in the non-virtual
137       // multiple inheritance case.
138       if (ML.VBase || !ML.VFPtrOffset.isZero())
139         return 0;
140     }
141     return MD->getParent();
142   }
143 
144   llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
145                                                 GlobalDecl GD,
146                                                 llvm::Value *This);
147 
148   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
149                                  FunctionArgList &Params);
150 
151   llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
152       CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
153 
154   void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
155 
156   unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
157                                       const CXXConstructorDecl *D,
158                                       CXXCtorType Type, bool ForVirtualBase,
159                                       bool Delegating, CallArgList &Args);
160 
161   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
162                           CXXDtorType Type, bool ForVirtualBase,
163                           bool Delegating, llvm::Value *This);
164 
165   void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
166 
167   llvm::Value *getVTableAddressPointInStructor(
168       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
169       BaseSubobject Base, const CXXRecordDecl *NearestVBase,
170       bool &NeedsVirtualOffset);
171 
172   llvm::Constant *
173   getVTableAddressPointForConstExpr(BaseSubobject Base,
174                                     const CXXRecordDecl *VTableClass);
175 
176   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
177                                         CharUnits VPtrOffset);
178 
179   llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
180                                          llvm::Value *This, llvm::Type *Ty);
181 
182   void EmitVirtualDestructorCall(CodeGenFunction &CGF,
183                                  const CXXDestructorDecl *Dtor,
184                                  CXXDtorType DtorType, SourceLocation CallLoc,
185                                  llvm::Value *This);
186 
187   void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
188                                         CallArgList &CallArgs) {
189     assert(GD.getDtorType() == Dtor_Deleting &&
190            "Only deleting destructor thunks are available in this ABI");
191     CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
192                              CGM.getContext().IntTy);
193   }
194 
195   void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
196 
197   llvm::GlobalVariable *
198   getAddrOfVBTable(const VBTableInfo &VBT, const CXXRecordDecl *RD,
199                    llvm::GlobalVariable::LinkageTypes Linkage);
200 
201   void emitVBTableDefinition(const VBTableInfo &VBT, const CXXRecordDecl *RD,
202                              llvm::GlobalVariable *GV) const;
203 
204   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
205     Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
206   }
207 
208   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
209                                      const ThisAdjustment &TA);
210 
211   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
212                                        const ReturnAdjustment &RA);
213 
214   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
215                        llvm::GlobalVariable *DeclPtr,
216                        bool PerformInit);
217 
218   // ==== Notes on array cookies =========
219   //
220   // MSVC seems to only use cookies when the class has a destructor; a
221   // two-argument usual array deallocation function isn't sufficient.
222   //
223   // For example, this code prints "100" and "1":
224   //   struct A {
225   //     char x;
226   //     void *operator new[](size_t sz) {
227   //       printf("%u\n", sz);
228   //       return malloc(sz);
229   //     }
230   //     void operator delete[](void *p, size_t sz) {
231   //       printf("%u\n", sz);
232   //       free(p);
233   //     }
234   //   };
235   //   int main() {
236   //     A *p = new A[100];
237   //     delete[] p;
238   //   }
239   // Whereas it prints "104" and "104" if you give A a destructor.
240 
241   bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
242   bool requiresArrayCookie(const CXXNewExpr *expr);
243   CharUnits getArrayCookieSizeImpl(QualType type);
244   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
245                                      llvm::Value *NewPtr,
246                                      llvm::Value *NumElements,
247                                      const CXXNewExpr *expr,
248                                      QualType ElementType);
249   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
250                                    llvm::Value *allocPtr,
251                                    CharUnits cookieSize);
252 
253 private:
254   MicrosoftMangleContext &getMangleContext() {
255     return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
256   }
257 
258   llvm::Constant *getZeroInt() {
259     return llvm::ConstantInt::get(CGM.IntTy, 0);
260   }
261 
262   llvm::Constant *getAllOnesInt() {
263     return  llvm::Constant::getAllOnesValue(CGM.IntTy);
264   }
265 
266   llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
267     return C ? C : getZeroInt();
268   }
269 
270   llvm::Value *getValueOrZeroInt(llvm::Value *C) {
271     return C ? C : getZeroInt();
272   }
273 
274   void
275   GetNullMemberPointerFields(const MemberPointerType *MPT,
276                              llvm::SmallVectorImpl<llvm::Constant *> &fields);
277 
278   /// \brief Shared code for virtual base adjustment.  Returns the offset from
279   /// the vbptr to the virtual base.  Optionally returns the address of the
280   /// vbptr itself.
281   llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
282                                        llvm::Value *Base,
283                                        llvm::Value *VBPtrOffset,
284                                        llvm::Value *VBTableOffset,
285                                        llvm::Value **VBPtr = 0);
286 
287   llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
288                                        llvm::Value *Base,
289                                        int32_t VBPtrOffset,
290                                        int32_t VBTableOffset,
291                                        llvm::Value **VBPtr = 0) {
292     llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
293                 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
294     return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
295   }
296 
297   /// \brief Performs a full virtual base adjustment.  Used to dereference
298   /// pointers to members of virtual bases.
299   llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
300                                  llvm::Value *Base,
301                                  llvm::Value *VirtualBaseAdjustmentOffset,
302                                  llvm::Value *VBPtrOffset /* optional */);
303 
304   /// \brief Emits a full member pointer with the fields common to data and
305   /// function member pointers.
306   llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
307                                         bool IsMemberFunction,
308                                         const CXXRecordDecl *RD,
309                                         CharUnits NonVirtualBaseAdjustment);
310 
311   llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
312                                      const CXXMethodDecl *MD,
313                                      CharUnits NonVirtualBaseAdjustment);
314 
315   bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
316                                    llvm::Constant *MP);
317 
318   /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
319   void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
320 
321   /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
322   const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
323 
324   /// \brief Generate a thunk for calling a virtual member function MD.
325   llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
326                                          StringRef ThunkName);
327 
328 public:
329   virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
330 
331   virtual bool isZeroInitializable(const MemberPointerType *MPT);
332 
333   virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
334 
335   virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
336                                                 CharUnits offset);
337   virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
338   virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
339 
340   virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
341                                                    llvm::Value *L,
342                                                    llvm::Value *R,
343                                                    const MemberPointerType *MPT,
344                                                    bool Inequality);
345 
346   virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
347                                                   llvm::Value *MemPtr,
348                                                   const MemberPointerType *MPT);
349 
350   virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
351                                                     llvm::Value *Base,
352                                                     llvm::Value *MemPtr,
353                                                   const MemberPointerType *MPT);
354 
355   virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
356                                                    const CastExpr *E,
357                                                    llvm::Value *Src);
358 
359   virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
360                                                       llvm::Constant *Src);
361 
362   virtual llvm::Value *
363   EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
364                                   llvm::Value *&This,
365                                   llvm::Value *MemPtr,
366                                   const MemberPointerType *MPT);
367 
368 private:
369   typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
370   typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
371   /// \brief All the vftables that have been referenced.
372   VFTablesMapTy VFTablesMap;
373 
374   /// \brief This set holds the record decls we've deferred vtable emission for.
375   llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
376 
377 
378   /// \brief All the vbtables which have been referenced.
379   llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
380 
381   /// Info on the global variable used to guard initialization of static locals.
382   /// The BitIndex field is only used for externally invisible declarations.
383   struct GuardInfo {
384     GuardInfo() : Guard(0), BitIndex(0) {}
385     llvm::GlobalVariable *Guard;
386     unsigned BitIndex;
387   };
388 
389   /// Map from DeclContext to the current guard variable.  We assume that the
390   /// AST is visited in source code order.
391   llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
392 };
393 
394 }
395 
396 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
397                                                      llvm::Value *ptr,
398                                                      QualType type) {
399   // FIXME: implement
400   return ptr;
401 }
402 
403 llvm::Value *
404 MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
405                                            llvm::Value *This,
406                                            const CXXRecordDecl *ClassDecl,
407                                            const CXXRecordDecl *BaseClassDecl) {
408   int64_t VBPtrChars =
409       getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
410   llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
411   CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
412   CharUnits VBTableChars =
413       IntSize *
414       CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
415   llvm::Value *VBTableOffset =
416     llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
417 
418   llvm::Value *VBPtrToNewBase =
419     GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
420   VBPtrToNewBase =
421     CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
422   return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
423 }
424 
425 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
426   return isa<CXXConstructorDecl>(GD.getDecl());
427 }
428 
429 void MicrosoftCXXABI::BuildConstructorSignature(
430     const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy,
431     SmallVectorImpl<CanQualType> &ArgTys) {
432 
433   // All parameters are already in place except is_most_derived, which goes
434   // after 'this' if it's variadic and last if it's not.
435 
436   const CXXRecordDecl *Class = Ctor->getParent();
437   const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>();
438   if (Class->getNumVBases()) {
439     if (FPT->isVariadic())
440       ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
441     else
442       ArgTys.push_back(CGM.getContext().IntTy);
443   }
444 }
445 
446 llvm::BasicBlock *
447 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
448                                                const CXXRecordDecl *RD) {
449   llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
450   assert(IsMostDerivedClass &&
451          "ctor for a class with virtual bases must have an implicit parameter");
452   llvm::Value *IsCompleteObject =
453     CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
454 
455   llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
456   llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
457   CGF.Builder.CreateCondBr(IsCompleteObject,
458                            CallVbaseCtorsBB, SkipVbaseCtorsBB);
459 
460   CGF.EmitBlock(CallVbaseCtorsBB);
461 
462   // Fill in the vbtable pointers here.
463   EmitVBPtrStores(CGF, RD);
464 
465   // CGF will put the base ctor calls in this basic block for us later.
466 
467   return SkipVbaseCtorsBB;
468 }
469 
470 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
471     CodeGenFunction &CGF, const CXXRecordDecl *RD) {
472   // In most cases, an override for a vbase virtual method can adjust
473   // the "this" parameter by applying a constant offset.
474   // However, this is not enough while a constructor or a destructor of some
475   // class X is being executed if all the following conditions are met:
476   //  - X has virtual bases, (1)
477   //  - X overrides a virtual method M of a vbase Y, (2)
478   //  - X itself is a vbase of the most derived class.
479   //
480   // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
481   // which holds the extra amount of "this" adjustment we must do when we use
482   // the X vftables (i.e. during X ctor or dtor).
483   // Outside the ctors and dtors, the values of vtorDisps are zero.
484 
485   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
486   typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
487   const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
488   CGBuilderTy &Builder = CGF.Builder;
489 
490   unsigned AS =
491       cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
492   llvm::Value *Int8This = 0;  // Initialize lazily.
493 
494   for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
495         I != E; ++I) {
496     if (!I->second.hasVtorDisp())
497       continue;
498 
499     llvm::Value *VBaseOffset =
500         GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
501     // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
502     // just to Trunc back immediately.
503     VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
504     uint64_t ConstantVBaseOffset =
505         Layout.getVBaseClassOffset(I->first).getQuantity();
506 
507     // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
508     llvm::Value *VtorDispValue = Builder.CreateSub(
509         VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
510         "vtordisp.value");
511 
512     if (!Int8This)
513       Int8This = Builder.CreateBitCast(getThisValue(CGF),
514                                        CGF.Int8Ty->getPointerTo(AS));
515     llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
516     // vtorDisp is always the 32-bits before the vbase in the class layout.
517     VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
518     VtorDispPtr = Builder.CreateBitCast(
519         VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
520 
521     Builder.CreateStore(VtorDispValue, VtorDispPtr);
522   }
523 }
524 
525 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
526   // There's only one constructor type in this ABI.
527   CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
528 }
529 
530 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
531                                       const CXXRecordDecl *RD) {
532   llvm::Value *ThisInt8Ptr =
533     CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
534   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
535 
536   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
537   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
538     const VBTableInfo *VBT = (*VBGlobals.VBTables)[I];
539     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
540     const ASTRecordLayout &SubobjectLayout =
541         CGM.getContext().getASTRecordLayout(VBT->BaseWithVBPtr);
542     CharUnits Offs = VBT->NonVirtualOffset;
543     Offs += SubobjectLayout.getVBPtrOffset();
544     if (VBT->getVBaseWithVBPtr())
545       Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVBPtr());
546     llvm::Value *VBPtr =
547         CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
548     VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0),
549                                       "vbptr." + VBT->ReusingBase->getName());
550     CGF.Builder.CreateStore(GV, VBPtr);
551   }
552 }
553 
554 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
555                                                CXXDtorType Type,
556                                                CanQualType &ResTy,
557                                         SmallVectorImpl<CanQualType> &ArgTys) {
558   // 'this' is already in place
559 
560   // TODO: 'for base' flag
561 
562   if (Type == Dtor_Deleting) {
563     // The scalar deleting destructor takes an implicit int parameter.
564     ArgTys.push_back(CGM.getContext().IntTy);
565   }
566 }
567 
568 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
569   // The TU defining a dtor is only guaranteed to emit a base destructor.  All
570   // other destructor variants are delegating thunks.
571   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
572 }
573 
574 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
575     CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
576   GD = GD.getCanonicalDecl();
577   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
578   // FIXME: consider splitting the vdtor vs regular method code into two
579   // functions.
580 
581   GlobalDecl LookupGD = GD;
582   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
583     // Complete dtors take a pointer to the complete object,
584     // thus don't need adjustment.
585     if (GD.getDtorType() == Dtor_Complete)
586       return This;
587 
588     // There's only Dtor_Deleting in vftable but it shares the this adjustment
589     // with the base one, so look up the deleting one instead.
590     LookupGD = GlobalDecl(DD, Dtor_Deleting);
591   }
592   MicrosoftVTableContext::MethodVFTableLocation ML =
593       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
594 
595   unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
596   llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
597   CharUnits StaticOffset = ML.VFPtrOffset;
598   if (ML.VBase) {
599     bool AvoidVirtualOffset = false;
600     if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
601       // A base destructor can only be called from a complete destructor of the
602       // same record type or another destructor of a more derived type;
603       // or a constructor of the same record type if an exception is thrown.
604       assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
605              isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
606       const CXXRecordDecl *CurRD =
607           cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
608 
609       if (MD->getParent() == CurRD) {
610         if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
611           assert(CGF.CurGD.getDtorType() == Dtor_Complete);
612         if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
613           assert(CGF.CurGD.getCtorType() == Ctor_Complete);
614         // We're calling the main base dtor from a complete structor,
615         // so we know the "this" offset statically.
616         AvoidVirtualOffset = true;
617       } else {
618         // Let's see if we try to call a destructor of a non-virtual base.
619         for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
620              E = CurRD->bases_end(); I != E; ++I) {
621           if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
622             continue;
623           // If we call a base destructor for a non-virtual base, we statically
624           // know where it expects the vfptr and "this" to be.
625           // The total offset should reflect the adjustment done by
626           // adjustThisParameterInVirtualFunctionPrologue().
627           AvoidVirtualOffset = true;
628           break;
629         }
630       }
631     }
632 
633     if (AvoidVirtualOffset) {
634       const ASTRecordLayout &Layout =
635           CGF.getContext().getASTRecordLayout(MD->getParent());
636       StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
637     } else {
638       This = CGF.Builder.CreateBitCast(This, charPtrTy);
639       llvm::Value *VBaseOffset =
640           GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
641       This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
642     }
643   }
644   if (!StaticOffset.isZero()) {
645     assert(StaticOffset.isPositive());
646     This = CGF.Builder.CreateBitCast(This, charPtrTy);
647     if (ML.VBase) {
648       // Non-virtual adjustment might result in a pointer outside the allocated
649       // object, e.g. if the final overrider class is laid out after the virtual
650       // base that declares a method in the most derived class.
651       // FIXME: Update the code that emits this adjustment in thunks prologues.
652       This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
653     } else {
654       This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
655                                                     StaticOffset.getQuantity());
656     }
657   }
658   return This;
659 }
660 
661 static bool IsDeletingDtor(GlobalDecl GD) {
662   const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
663   if (isa<CXXDestructorDecl>(MD)) {
664     return GD.getDtorType() == Dtor_Deleting;
665   }
666   return false;
667 }
668 
669 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
670                                                 QualType &ResTy,
671                                                 FunctionArgList &Params) {
672   ASTContext &Context = getContext();
673   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
674   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
675   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
676     ImplicitParamDecl *IsMostDerived
677       = ImplicitParamDecl::Create(Context, 0,
678                                   CGF.CurGD.getDecl()->getLocation(),
679                                   &Context.Idents.get("is_most_derived"),
680                                   Context.IntTy);
681     // The 'most_derived' parameter goes second if the ctor is variadic and last
682     // if it's not.  Dtors can't be variadic.
683     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
684     if (FPT->isVariadic())
685       Params.insert(Params.begin() + 1, IsMostDerived);
686     else
687       Params.push_back(IsMostDerived);
688     getStructorImplicitParamDecl(CGF) = IsMostDerived;
689   } else if (IsDeletingDtor(CGF.CurGD)) {
690     ImplicitParamDecl *ShouldDelete
691       = ImplicitParamDecl::Create(Context, 0,
692                                   CGF.CurGD.getDecl()->getLocation(),
693                                   &Context.Idents.get("should_call_delete"),
694                                   Context.IntTy);
695     Params.push_back(ShouldDelete);
696     getStructorImplicitParamDecl(CGF) = ShouldDelete;
697   }
698 }
699 
700 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
701     CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
702   GD = GD.getCanonicalDecl();
703   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
704 
705   GlobalDecl LookupGD = GD;
706   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
707     // Complete destructors take a pointer to the complete object as a
708     // parameter, thus don't need this adjustment.
709     if (GD.getDtorType() == Dtor_Complete)
710       return This;
711 
712     // There's no Dtor_Base in vftable but it shares the this adjustment with
713     // the deleting one, so look it up instead.
714     LookupGD = GlobalDecl(DD, Dtor_Deleting);
715   }
716 
717   // In this ABI, every virtual function takes a pointer to one of the
718   // subobjects that first defines it as the 'this' parameter, rather than a
719   // pointer to the final overrider subobject. Thus, we need to adjust it back
720   // to the final overrider subobject before use.
721   // See comments in the MicrosoftVFTableContext implementation for the details.
722 
723   MicrosoftVTableContext::MethodVFTableLocation ML =
724       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
725   CharUnits Adjustment = ML.VFPtrOffset;
726   if (ML.VBase) {
727     const ASTRecordLayout &DerivedLayout =
728         CGF.getContext().getASTRecordLayout(MD->getParent());
729     Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
730   }
731 
732   if (Adjustment.isZero())
733     return This;
734 
735   unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
736   llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
737              *thisTy = This->getType();
738 
739   This = CGF.Builder.CreateBitCast(This, charPtrTy);
740   assert(Adjustment.isPositive());
741   This =
742       CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
743   return CGF.Builder.CreateBitCast(This, thisTy);
744 }
745 
746 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
747   EmitThisParam(CGF);
748 
749   /// If this is a function that the ABI specifies returns 'this', initialize
750   /// the return slot to 'this' at the start of the function.
751   ///
752   /// Unlike the setting of return types, this is done within the ABI
753   /// implementation instead of by clients of CGCXXABI because:
754   /// 1) getThisValue is currently protected
755   /// 2) in theory, an ABI could implement 'this' returns some other way;
756   ///    HasThisReturn only specifies a contract, not the implementation
757   if (HasThisReturn(CGF.CurGD))
758     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
759 
760   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
761   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
762     assert(getStructorImplicitParamDecl(CGF) &&
763            "no implicit parameter for a constructor with virtual bases?");
764     getStructorImplicitParamValue(CGF)
765       = CGF.Builder.CreateLoad(
766           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
767           "is_most_derived");
768   }
769 
770   if (IsDeletingDtor(CGF.CurGD)) {
771     assert(getStructorImplicitParamDecl(CGF) &&
772            "no implicit parameter for a deleting destructor?");
773     getStructorImplicitParamValue(CGF)
774       = CGF.Builder.CreateLoad(
775           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
776           "should_call_delete");
777   }
778 }
779 
780 unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
781     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
782     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
783   assert(Type == Ctor_Complete || Type == Ctor_Base);
784 
785   // Check if we need a 'most_derived' parameter.
786   if (!D->getParent()->getNumVBases())
787     return 0;
788 
789   // Add the 'most_derived' argument second if we are variadic or last if not.
790   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
791   llvm::Value *MostDerivedArg =
792       llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
793   RValue RV = RValue::get(MostDerivedArg);
794   if (MostDerivedArg) {
795     if (FPT->isVariadic())
796       Args.insert(Args.begin() + 1,
797                   CallArg(RV, getContext().IntTy, /*needscopy=*/false));
798     else
799       Args.add(RV, getContext().IntTy);
800   }
801 
802   return 1;  // Added one arg.
803 }
804 
805 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
806                                          const CXXDestructorDecl *DD,
807                                          CXXDtorType Type, bool ForVirtualBase,
808                                          bool Delegating, llvm::Value *This) {
809   llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
810 
811   if (DD->isVirtual())
812     This = adjustThisArgumentForVirtualCall(CGF, GlobalDecl(DD, Type), This);
813 
814   // FIXME: Provide a source location here.
815   CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
816                         /*ImplicitParam=*/0, /*ImplicitParamTy=*/QualType(), 0, 0);
817 }
818 
819 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
820                                             const CXXRecordDecl *RD) {
821   MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
822   MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
823   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
824 
825   for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
826        E = VFPtrs.end(); I != E; ++I) {
827     llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
828     if (VTable->hasInitializer())
829       continue;
830 
831     const VTableLayout &VTLayout =
832         VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
833     llvm::Constant *Init = CGVT.CreateVTableInitializer(
834         RD, VTLayout.vtable_component_begin(),
835         VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
836         VTLayout.getNumVTableThunks());
837     VTable->setInitializer(Init);
838 
839     VTable->setLinkage(Linkage);
840     CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
841   }
842 }
843 
844 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
845     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
846     const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
847   NeedsVirtualOffset = (NearestVBase != 0);
848 
849   llvm::Value *VTableAddressPoint =
850       getAddrOfVTable(VTableClass, Base.getBaseOffset());
851   if (!VTableAddressPoint) {
852     assert(Base.getBase()->getNumVBases() &&
853            !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
854   }
855   return VTableAddressPoint;
856 }
857 
858 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
859                               const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
860                               SmallString<256> &Name) {
861   llvm::raw_svector_ostream Out(Name);
862   MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
863 }
864 
865 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
866     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
867   llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
868   assert(VTable && "Couldn't find a vftable for the given base?");
869   return VTable;
870 }
871 
872 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
873                                                        CharUnits VPtrOffset) {
874   // getAddrOfVTable may return 0 if asked to get an address of a vtable which
875   // shouldn't be used in the given record type. We want to cache this result in
876   // VFTablesMap, thus a simple zero check is not sufficient.
877   VFTableIdTy ID(RD, VPtrOffset);
878   VFTablesMapTy::iterator I;
879   bool Inserted;
880   llvm::tie(I, Inserted) = VFTablesMap.insert(
881       std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
882   if (!Inserted)
883     return I->second;
884 
885   llvm::GlobalVariable *&VTable = I->second;
886 
887   MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
888   const MicrosoftVTableContext::VFPtrListTy &VFPtrs =
889       VTContext.getVFPtrOffsets(RD);
890 
891   if (DeferredVFTables.insert(RD)) {
892     // We haven't processed this record type before.
893     // Queue up this v-table for possible deferred emission.
894     CGM.addDeferredVTable(RD);
895 
896 #ifndef NDEBUG
897     // Create all the vftables at once in order to make sure each vftable has
898     // a unique mangled name.
899     llvm::StringSet<> ObservedMangledNames;
900     for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
901       SmallString<256> Name;
902       mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
903       if (!ObservedMangledNames.insert(Name.str()))
904         llvm_unreachable("Already saw this mangling before?");
905     }
906 #endif
907   }
908 
909   for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
910     if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
911       continue;
912 
913     llvm::ArrayType *ArrayType = llvm::ArrayType::get(
914         CGM.Int8PtrTy,
915         VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
916             .getNumVTableComponents());
917 
918     SmallString<256> Name;
919     mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
920     VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
921         Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
922     VTable->setUnnamedAddr(true);
923     break;
924   }
925 
926   return VTable;
927 }
928 
929 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
930                                                         GlobalDecl GD,
931                                                         llvm::Value *This,
932                                                         llvm::Type *Ty) {
933   GD = GD.getCanonicalDecl();
934   CGBuilderTy &Builder = CGF.Builder;
935 
936   Ty = Ty->getPointerTo()->getPointerTo();
937   llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
938   llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
939 
940   MicrosoftVTableContext::MethodVFTableLocation ML =
941       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
942   llvm::Value *VFuncPtr =
943       Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
944   return Builder.CreateLoad(VFuncPtr);
945 }
946 
947 void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
948                                                 const CXXDestructorDecl *Dtor,
949                                                 CXXDtorType DtorType,
950                                                 SourceLocation CallLoc,
951                                                 llvm::Value *This) {
952   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
953 
954   // We have only one destructor in the vftable but can get both behaviors
955   // by passing an implicit int parameter.
956   GlobalDecl GD(Dtor, Dtor_Deleting);
957   const CGFunctionInfo *FInfo =
958       &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
959   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
960   llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
961 
962   ASTContext &Context = CGF.getContext();
963   llvm::Value *ImplicitParam =
964       llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
965                              DtorType == Dtor_Deleting);
966 
967   This = adjustThisArgumentForVirtualCall(CGF, GD, This);
968   CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
969                         ImplicitParam, Context.IntTy, 0, 0);
970 }
971 
972 const VBTableGlobals &
973 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
974   // At this layer, we can key the cache off of a single class, which is much
975   // easier than caching each vbtable individually.
976   llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
977   bool Added;
978   llvm::tie(Entry, Added) = VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
979   VBTableGlobals &VBGlobals = Entry->second;
980   if (!Added)
981     return VBGlobals;
982 
983   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
984   VBGlobals.VBTables = &Context.enumerateVBTables(RD);
985 
986   // Cache the globals for all vbtables so we don't have to recompute the
987   // mangled names.
988   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
989   for (VBTableVector::const_iterator I = VBGlobals.VBTables->begin(),
990                                      E = VBGlobals.VBTables->end();
991        I != E; ++I) {
992     VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
993   }
994 
995   return VBGlobals;
996 }
997 
998 llvm::Function *
999 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
1000                                         StringRef ThunkName) {
1001   // If the thunk has been generated previously, just return it.
1002   if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1003     return cast<llvm::Function>(GV);
1004 
1005   // Create the llvm::Function.
1006   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
1007   llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1008   llvm::Function *ThunkFn =
1009       llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1010                              ThunkName.str(), &CGM.getModule());
1011   assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1012 
1013   ThunkFn->setLinkage(MD->isExternallyVisible()
1014                           ? llvm::GlobalValue::LinkOnceODRLinkage
1015                           : llvm::GlobalValue::InternalLinkage);
1016 
1017   CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1018   CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1019 
1020   // Start codegen.
1021   CodeGenFunction CGF(CGM);
1022   CGF.StartThunk(ThunkFn, MD, FnInfo);
1023 
1024   // Get to the Callee.
1025   llvm::Value *This = CGF.LoadCXXThis();
1026   llvm::Value *Callee = getVirtualFunctionPointer(CGF, MD, This, ThunkTy);
1027 
1028   // Make the call and return the result.
1029   CGF.EmitCallAndReturnForThunk(MD, Callee, 0);
1030 
1031   return ThunkFn;
1032 }
1033 
1034 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1035   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1036   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1037     const VBTableInfo *VBT = (*VBGlobals.VBTables)[I];
1038     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1039     emitVBTableDefinition(*VBT, RD, GV);
1040   }
1041 }
1042 
1043 llvm::GlobalVariable *
1044 MicrosoftCXXABI::getAddrOfVBTable(const VBTableInfo &VBT,
1045                                   const CXXRecordDecl *RD,
1046                                   llvm::GlobalVariable::LinkageTypes Linkage) {
1047   SmallString<256> OutName;
1048   llvm::raw_svector_ostream Out(OutName);
1049   MicrosoftMangleContext &Mangler =
1050       cast<MicrosoftMangleContext>(CGM.getCXXABI().getMangleContext());
1051   Mangler.mangleCXXVBTable(RD, VBT.MangledPath, Out);
1052   Out.flush();
1053   StringRef Name = OutName.str();
1054 
1055   llvm::ArrayType *VBTableType =
1056       llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1057 
1058   assert(!CGM.getModule().getNamedGlobal(Name) &&
1059          "vbtable with this name already exists: mangling bug?");
1060   llvm::GlobalVariable *GV =
1061       CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1062   GV->setUnnamedAddr(true);
1063   return GV;
1064 }
1065 
1066 void MicrosoftCXXABI::emitVBTableDefinition(const VBTableInfo &VBT,
1067                                             const CXXRecordDecl *RD,
1068                                             llvm::GlobalVariable *GV) const {
1069   const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1070 
1071   assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1072          "should only emit vbtables for classes with vbtables");
1073 
1074   const ASTRecordLayout &BaseLayout =
1075     CGM.getContext().getASTRecordLayout(VBT.BaseWithVBPtr);
1076   const ASTRecordLayout &DerivedLayout =
1077     CGM.getContext().getASTRecordLayout(RD);
1078 
1079   SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(), 0);
1080 
1081   // The offset from ReusingBase's vbptr to itself always leads.
1082   CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1083   Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1084 
1085   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1086   for (CXXRecordDecl::base_class_const_iterator I = ReusingBase->vbases_begin(),
1087                                                 E = ReusingBase->vbases_end();
1088        I != E; ++I) {
1089     const CXXRecordDecl *VBase = I->getType()->getAsCXXRecordDecl();
1090     CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1091     assert(!Offset.isNegative());
1092 
1093     // Make it relative to the subobject vbptr.
1094     CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1095     if (VBT.getVBaseWithVBPtr())
1096       CompleteVBPtrOffset +=
1097           DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVBPtr());
1098     Offset -= CompleteVBPtrOffset;
1099 
1100     unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1101     assert(Offsets[VBIndex] == 0 && "The same vbindex seen twice?");
1102     Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1103   }
1104 
1105   assert(Offsets.size() ==
1106          cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1107                                ->getElementType())->getNumElements());
1108   llvm::ArrayType *VBTableType =
1109     llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1110   llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1111   GV->setInitializer(Init);
1112 
1113   // Set the right visibility.
1114   CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForVTable);
1115 }
1116 
1117 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1118                                                     llvm::Value *This,
1119                                                     const ThisAdjustment &TA) {
1120   if (TA.isEmpty())
1121     return This;
1122 
1123   llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1124 
1125   if (!TA.Virtual.isEmpty()) {
1126     assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1127     // Adjust the this argument based on the vtordisp value.
1128     llvm::Value *VtorDispPtr =
1129         CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1130     VtorDispPtr =
1131         CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1132     llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1133     V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1134 
1135     if (TA.Virtual.Microsoft.VBPtrOffset) {
1136       // If the final overrider is defined in a virtual base other than the one
1137       // that holds the vfptr, we have to use a vtordispex thunk which looks up
1138       // the vbtable of the derived class.
1139       assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1140       assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1141       llvm::Value *VBPtr;
1142       llvm::Value *VBaseOffset =
1143           GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1144                                   TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1145       V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1146     }
1147   }
1148 
1149   if (TA.NonVirtual) {
1150     // Non-virtual adjustment might result in a pointer outside the allocated
1151     // object, e.g. if the final overrider class is laid out after the virtual
1152     // base that declares a method in the most derived class.
1153     V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1154   }
1155 
1156   // Don't need to bitcast back, the call CodeGen will handle this.
1157   return V;
1158 }
1159 
1160 llvm::Value *
1161 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1162                                          const ReturnAdjustment &RA) {
1163   if (RA.isEmpty())
1164     return Ret;
1165 
1166   llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1167 
1168   if (RA.Virtual.Microsoft.VBIndex) {
1169     assert(RA.Virtual.Microsoft.VBIndex > 0);
1170     int32_t IntSize =
1171         getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1172     llvm::Value *VBPtr;
1173     llvm::Value *VBaseOffset =
1174         GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1175                                 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1176     V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1177   }
1178 
1179   if (RA.NonVirtual)
1180     V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1181 
1182   // Cast back to the original type.
1183   return CGF.Builder.CreateBitCast(V, Ret->getType());
1184 }
1185 
1186 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1187                                    QualType elementType) {
1188   // Microsoft seems to completely ignore the possibility of a
1189   // two-argument usual deallocation function.
1190   return elementType.isDestructedType();
1191 }
1192 
1193 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1194   // Microsoft seems to completely ignore the possibility of a
1195   // two-argument usual deallocation function.
1196   return expr->getAllocatedType().isDestructedType();
1197 }
1198 
1199 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1200   // The array cookie is always a size_t; we then pad that out to the
1201   // alignment of the element type.
1202   ASTContext &Ctx = getContext();
1203   return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1204                   Ctx.getTypeAlignInChars(type));
1205 }
1206 
1207 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1208                                                   llvm::Value *allocPtr,
1209                                                   CharUnits cookieSize) {
1210   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1211   llvm::Value *numElementsPtr =
1212     CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1213   return CGF.Builder.CreateLoad(numElementsPtr);
1214 }
1215 
1216 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1217                                                     llvm::Value *newPtr,
1218                                                     llvm::Value *numElements,
1219                                                     const CXXNewExpr *expr,
1220                                                     QualType elementType) {
1221   assert(requiresArrayCookie(expr));
1222 
1223   // The size of the cookie.
1224   CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1225 
1226   // Compute an offset to the cookie.
1227   llvm::Value *cookiePtr = newPtr;
1228 
1229   // Write the number of elements into the appropriate slot.
1230   unsigned AS = newPtr->getType()->getPointerAddressSpace();
1231   llvm::Value *numElementsPtr
1232     = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1233   CGF.Builder.CreateStore(numElements, numElementsPtr);
1234 
1235   // Finally, compute a pointer to the actual data buffer by skipping
1236   // over the cookie completely.
1237   return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1238                                                 cookieSize.getQuantity());
1239 }
1240 
1241 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
1242                                       llvm::GlobalVariable *GV,
1243                                       bool PerformInit) {
1244   // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1245   // threadsafe.  Since the user may be linking in inline functions compiled by
1246   // cl.exe, there's no reason to provide a false sense of security by using
1247   // critical sections here.
1248 
1249   if (D.getTLSKind())
1250     CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1251 
1252   CGBuilderTy &Builder = CGF.Builder;
1253   llvm::IntegerType *GuardTy = CGF.Int32Ty;
1254   llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1255 
1256   // Get the guard variable for this function if we have one already.
1257   GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1258 
1259   unsigned BitIndex;
1260   if (D.isExternallyVisible()) {
1261     // Externally visible variables have to be numbered in Sema to properly
1262     // handle unreachable VarDecls.
1263     BitIndex = getContext().getManglingNumber(&D);
1264     assert(BitIndex > 0);
1265     BitIndex--;
1266   } else {
1267     // Non-externally visible variables are numbered here in CodeGen.
1268     BitIndex = GI.BitIndex++;
1269   }
1270 
1271   if (BitIndex >= 32) {
1272     if (D.isExternallyVisible())
1273       ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1274     BitIndex %= 32;
1275     GI.Guard = 0;
1276   }
1277 
1278   // Lazily create the i32 bitfield for this function.
1279   if (!GI.Guard) {
1280     // Mangle the name for the guard.
1281     SmallString<256> GuardName;
1282     {
1283       llvm::raw_svector_ostream Out(GuardName);
1284       getMangleContext().mangleStaticGuardVariable(&D, Out);
1285       Out.flush();
1286     }
1287 
1288     // Create the guard variable with a zero-initializer.  Just absorb linkage
1289     // and visibility from the guarded variable.
1290     GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1291                                      GV->getLinkage(), Zero, GuardName.str());
1292     GI.Guard->setVisibility(GV->getVisibility());
1293   } else {
1294     assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1295            "static local from the same function had different linkage");
1296   }
1297 
1298   // Pseudo code for the test:
1299   // if (!(GuardVar & MyGuardBit)) {
1300   //   GuardVar |= MyGuardBit;
1301   //   ... initialize the object ...;
1302   // }
1303 
1304   // Test our bit from the guard variable.
1305   llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1306   llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1307   llvm::Value *IsInitialized =
1308       Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1309   llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1310   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1311   Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1312 
1313   // Set our bit in the guard variable and emit the initializer and add a global
1314   // destructor if appropriate.
1315   CGF.EmitBlock(InitBlock);
1316   Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1317   CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1318   Builder.CreateBr(EndBlock);
1319 
1320   // Continue.
1321   CGF.EmitBlock(EndBlock);
1322 }
1323 
1324 // Member pointer helpers.
1325 static bool hasVBPtrOffsetField(MSInheritanceAttr::Spelling Inheritance) {
1326   return Inheritance == MSInheritanceAttr::Keyword_unspecified_inheritance;
1327 }
1328 
1329 static bool hasOnlyOneField(bool IsMemberFunction,
1330                             MSInheritanceAttr::Spelling Inheritance) {
1331   if (IsMemberFunction)
1332     return Inheritance <= MSInheritanceAttr::Keyword_single_inheritance;
1333   return Inheritance <= MSInheritanceAttr::Keyword_multiple_inheritance;
1334 }
1335 
1336 // Only member pointers to functions need a this adjustment, since it can be
1337 // combined with the field offset for data pointers.
1338 static bool
1339 hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
1340                                  MSInheritanceAttr::Spelling Inheritance) {
1341   return IsMemberFunction &&
1342          Inheritance >= MSInheritanceAttr::Keyword_multiple_inheritance;
1343 }
1344 
1345 static bool
1346 hasVirtualBaseAdjustmentField(MSInheritanceAttr::Spelling Inheritance) {
1347   return Inheritance >= MSInheritanceAttr::Keyword_virtual_inheritance;
1348 }
1349 
1350 // Use zero for the field offset of a null data member pointer if we can
1351 // guarantee that zero is not a valid field offset, or if the member pointer has
1352 // multiple fields.  Polymorphic classes have a vfptr at offset zero, so we can
1353 // use zero for null.  If there are multiple fields, we can use zero even if it
1354 // is a valid field offset because null-ness testing will check the other
1355 // fields.
1356 static bool nullFieldOffsetIsZero(const CXXRecordDecl *RD) {
1357   return RD->getMSInheritanceModel() >=
1358              MSInheritanceAttr::Keyword_virtual_inheritance ||
1359          (RD->hasDefinition() && RD->isPolymorphic());
1360 }
1361 
1362 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1363   // Null-ness for function memptrs only depends on the first field, which is
1364   // the function pointer.  The rest don't matter, so we can zero initialize.
1365   if (MPT->isMemberFunctionPointer())
1366     return true;
1367 
1368   // The virtual base adjustment field is always -1 for null, so if we have one
1369   // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
1370   // valid field offset.
1371   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1372   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1373   return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1374           nullFieldOffsetIsZero(RD));
1375 }
1376 
1377 llvm::Type *
1378 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1379   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1380   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1381   llvm::SmallVector<llvm::Type *, 4> fields;
1382   if (MPT->isMemberFunctionPointer())
1383     fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
1384   else
1385     fields.push_back(CGM.IntTy);  // FieldOffset
1386 
1387   if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1388                                        Inheritance))
1389     fields.push_back(CGM.IntTy);
1390   if (hasVBPtrOffsetField(Inheritance))
1391     fields.push_back(CGM.IntTy);
1392   if (hasVirtualBaseAdjustmentField(Inheritance))
1393     fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
1394 
1395   if (fields.size() == 1)
1396     return fields[0];
1397   return llvm::StructType::get(CGM.getLLVMContext(), fields);
1398 }
1399 
1400 void MicrosoftCXXABI::
1401 GetNullMemberPointerFields(const MemberPointerType *MPT,
1402                            llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1403   assert(fields.empty());
1404   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1405   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1406   if (MPT->isMemberFunctionPointer()) {
1407     // FunctionPointerOrVirtualThunk
1408     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1409   } else {
1410     if (nullFieldOffsetIsZero(RD))
1411       fields.push_back(getZeroInt());  // FieldOffset
1412     else
1413       fields.push_back(getAllOnesInt());  // FieldOffset
1414   }
1415 
1416   if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1417                                        Inheritance))
1418     fields.push_back(getZeroInt());
1419   if (hasVBPtrOffsetField(Inheritance))
1420     fields.push_back(getZeroInt());
1421   if (hasVirtualBaseAdjustmentField(Inheritance))
1422     fields.push_back(getAllOnesInt());
1423 }
1424 
1425 llvm::Constant *
1426 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
1427   llvm::SmallVector<llvm::Constant *, 4> fields;
1428   GetNullMemberPointerFields(MPT, fields);
1429   if (fields.size() == 1)
1430     return fields[0];
1431   llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1432   assert(Res->getType() == ConvertMemberPointerType(MPT));
1433   return Res;
1434 }
1435 
1436 llvm::Constant *
1437 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1438                                        bool IsMemberFunction,
1439                                        const CXXRecordDecl *RD,
1440                                        CharUnits NonVirtualBaseAdjustment)
1441 {
1442   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1443 
1444   // Single inheritance class member pointer are represented as scalars instead
1445   // of aggregates.
1446   if (hasOnlyOneField(IsMemberFunction, Inheritance))
1447     return FirstField;
1448 
1449   llvm::SmallVector<llvm::Constant *, 4> fields;
1450   fields.push_back(FirstField);
1451 
1452   if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
1453     fields.push_back(llvm::ConstantInt::get(
1454       CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
1455 
1456   if (hasVBPtrOffsetField(Inheritance)) {
1457     CharUnits Offs = CharUnits::Zero();
1458     if (RD->getNumVBases())
1459       Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
1460     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
1461   }
1462 
1463   // The rest of the fields are adjusted by conversions to a more derived class.
1464   if (hasVirtualBaseAdjustmentField(Inheritance))
1465     fields.push_back(getZeroInt());
1466 
1467   return llvm::ConstantStruct::getAnon(fields);
1468 }
1469 
1470 llvm::Constant *
1471 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1472                                        CharUnits offset) {
1473   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1474   llvm::Constant *FirstField =
1475     llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
1476   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1477                                CharUnits::Zero());
1478 }
1479 
1480 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1481   return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1482 }
1483 
1484 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1485                                                    QualType MPType) {
1486   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1487   const ValueDecl *MPD = MP.getMemberPointerDecl();
1488   if (!MPD)
1489     return EmitNullMemberPointer(MPT);
1490 
1491   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1492 
1493   // FIXME PR15713: Support virtual inheritance paths.
1494 
1495   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1496     return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
1497                               ThisAdjustment);
1498 
1499   CharUnits FieldOffset =
1500     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1501   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
1502 }
1503 
1504 llvm::Constant *
1505 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1506                                     const CXXMethodDecl *MD,
1507                                     CharUnits NonVirtualBaseAdjustment) {
1508   assert(MD->isInstance() && "Member function must not be static!");
1509   MD = MD->getCanonicalDecl();
1510   RD = RD->getMostRecentDecl();
1511   CodeGenTypes &Types = CGM.getTypes();
1512 
1513   llvm::Constant *FirstField;
1514   if (!MD->isVirtual()) {
1515     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1516     llvm::Type *Ty;
1517     // Check whether the function has a computable LLVM signature.
1518     if (Types.isFuncTypeConvertible(FPT)) {
1519       // The function has a computable LLVM signature; use the correct type.
1520       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1521     } else {
1522       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1523       // function type is incomplete.
1524       Ty = CGM.PtrDiffTy;
1525     }
1526     FirstField = CGM.GetAddrOfFunction(MD, Ty);
1527     FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1528   } else {
1529     MicrosoftVTableContext::MethodVFTableLocation ML =
1530         CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1531     if (MD->isVariadic()) {
1532       CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1533       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1534     } else if (!CGM.getTypes().isFuncTypeConvertible(
1535                     MD->getType()->castAs<FunctionType>())) {
1536       CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1537                                "incomplete return or parameter type");
1538       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1539     } else if (ML.VBase) {
1540       CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1541                                "member function in virtual base class");
1542       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1543     } else {
1544       SmallString<256> ThunkName;
1545       CharUnits PointerWidth = getContext().toCharUnitsFromBits(
1546           getContext().getTargetInfo().getPointerWidth(0));
1547       uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
1548       llvm::raw_svector_ostream Out(ThunkName);
1549       getMangleContext().mangleVirtualMemPtrThunk(MD, OffsetInVFTable, Out);
1550       Out.flush();
1551 
1552       llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str());
1553       FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1554     }
1555   }
1556 
1557   // The rest of the fields are common with data member pointers.
1558   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1559                                NonVirtualBaseAdjustment);
1560 }
1561 
1562 /// Member pointers are the same if they're either bitwise identical *or* both
1563 /// null.  Null-ness for function members is determined by the first field,
1564 /// while for data member pointers we must compare all fields.
1565 llvm::Value *
1566 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1567                                              llvm::Value *L,
1568                                              llvm::Value *R,
1569                                              const MemberPointerType *MPT,
1570                                              bool Inequality) {
1571   CGBuilderTy &Builder = CGF.Builder;
1572 
1573   // Handle != comparisons by switching the sense of all boolean operations.
1574   llvm::ICmpInst::Predicate Eq;
1575   llvm::Instruction::BinaryOps And, Or;
1576   if (Inequality) {
1577     Eq = llvm::ICmpInst::ICMP_NE;
1578     And = llvm::Instruction::Or;
1579     Or = llvm::Instruction::And;
1580   } else {
1581     Eq = llvm::ICmpInst::ICMP_EQ;
1582     And = llvm::Instruction::And;
1583     Or = llvm::Instruction::Or;
1584   }
1585 
1586   // If this is a single field member pointer (single inheritance), this is a
1587   // single icmp.
1588   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1589   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1590   if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
1591     return Builder.CreateICmp(Eq, L, R);
1592 
1593   // Compare the first field.
1594   llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1595   llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1596   llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1597 
1598   // Compare everything other than the first field.
1599   llvm::Value *Res = 0;
1600   llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1601   for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1602     llvm::Value *LF = Builder.CreateExtractValue(L, I);
1603     llvm::Value *RF = Builder.CreateExtractValue(R, I);
1604     llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1605     if (Res)
1606       Res = Builder.CreateBinOp(And, Res, Cmp);
1607     else
1608       Res = Cmp;
1609   }
1610 
1611   // Check if the first field is 0 if this is a function pointer.
1612   if (MPT->isMemberFunctionPointer()) {
1613     // (l1 == r1 && ...) || l0 == 0
1614     llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1615     llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1616     Res = Builder.CreateBinOp(Or, Res, IsZero);
1617   }
1618 
1619   // Combine the comparison of the first field, which must always be true for
1620   // this comparison to succeeed.
1621   return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1622 }
1623 
1624 llvm::Value *
1625 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1626                                             llvm::Value *MemPtr,
1627                                             const MemberPointerType *MPT) {
1628   CGBuilderTy &Builder = CGF.Builder;
1629   llvm::SmallVector<llvm::Constant *, 4> fields;
1630   // We only need one field for member functions.
1631   if (MPT->isMemberFunctionPointer())
1632     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1633   else
1634     GetNullMemberPointerFields(MPT, fields);
1635   assert(!fields.empty());
1636   llvm::Value *FirstField = MemPtr;
1637   if (MemPtr->getType()->isStructTy())
1638     FirstField = Builder.CreateExtractValue(MemPtr, 0);
1639   llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
1640 
1641   // For function member pointers, we only need to test the function pointer
1642   // field.  The other fields if any can be garbage.
1643   if (MPT->isMemberFunctionPointer())
1644     return Res;
1645 
1646   // Otherwise, emit a series of compares and combine the results.
1647   for (int I = 1, E = fields.size(); I < E; ++I) {
1648     llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1649     llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1650     Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1651   }
1652   return Res;
1653 }
1654 
1655 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1656                                                   llvm::Constant *Val) {
1657   // Function pointers are null if the pointer in the first field is null.
1658   if (MPT->isMemberFunctionPointer()) {
1659     llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1660       Val->getAggregateElement(0U) : Val;
1661     return FirstField->isNullValue();
1662   }
1663 
1664   // If it's not a function pointer and it's zero initializable, we can easily
1665   // check zero.
1666   if (isZeroInitializable(MPT) && Val->isNullValue())
1667     return true;
1668 
1669   // Otherwise, break down all the fields for comparison.  Hopefully these
1670   // little Constants are reused, while a big null struct might not be.
1671   llvm::SmallVector<llvm::Constant *, 4> Fields;
1672   GetNullMemberPointerFields(MPT, Fields);
1673   if (Fields.size() == 1) {
1674     assert(Val->getType()->isIntegerTy());
1675     return Val == Fields[0];
1676   }
1677 
1678   unsigned I, E;
1679   for (I = 0, E = Fields.size(); I != E; ++I) {
1680     if (Val->getAggregateElement(I) != Fields[I])
1681       break;
1682   }
1683   return I == E;
1684 }
1685 
1686 llvm::Value *
1687 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1688                                          llvm::Value *This,
1689                                          llvm::Value *VBPtrOffset,
1690                                          llvm::Value *VBTableOffset,
1691                                          llvm::Value **VBPtrOut) {
1692   CGBuilderTy &Builder = CGF.Builder;
1693   // Load the vbtable pointer from the vbptr in the instance.
1694   This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1695   llvm::Value *VBPtr =
1696     Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1697   if (VBPtrOut) *VBPtrOut = VBPtr;
1698   VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1699   llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1700 
1701   // Load an i32 offset from the vb-table.
1702   llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1703   VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1704   return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1705 }
1706 
1707 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
1708 // it.
1709 llvm::Value *
1710 MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1711                                    const CXXRecordDecl *RD, llvm::Value *Base,
1712                                    llvm::Value *VBTableOffset,
1713                                    llvm::Value *VBPtrOffset) {
1714   CGBuilderTy &Builder = CGF.Builder;
1715   Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1716   llvm::BasicBlock *OriginalBB = 0;
1717   llvm::BasicBlock *SkipAdjustBB = 0;
1718   llvm::BasicBlock *VBaseAdjustBB = 0;
1719 
1720   // In the unspecified inheritance model, there might not be a vbtable at all,
1721   // in which case we need to skip the virtual base lookup.  If there is a
1722   // vbtable, the first entry is a no-op entry that gives back the original
1723   // base, so look for a virtual base adjustment offset of zero.
1724   if (VBPtrOffset) {
1725     OriginalBB = Builder.GetInsertBlock();
1726     VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1727     SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1728     llvm::Value *IsVirtual =
1729       Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
1730                            "memptr.is_vbase");
1731     Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1732     CGF.EmitBlock(VBaseAdjustBB);
1733   }
1734 
1735   // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1736   // know the vbptr offset.
1737   if (!VBPtrOffset) {
1738     CharUnits offs = CharUnits::Zero();
1739     if (RD->getNumVBases())
1740       offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
1741     VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1742   }
1743   llvm::Value *VBPtr = 0;
1744   llvm::Value *VBaseOffs =
1745     GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
1746   llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1747 
1748   // Merge control flow with the case where we didn't have to adjust.
1749   if (VBaseAdjustBB) {
1750     Builder.CreateBr(SkipAdjustBB);
1751     CGF.EmitBlock(SkipAdjustBB);
1752     llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1753     Phi->addIncoming(Base, OriginalBB);
1754     Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1755     return Phi;
1756   }
1757   return AdjustedBase;
1758 }
1759 
1760 llvm::Value *
1761 MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1762                                               llvm::Value *Base,
1763                                               llvm::Value *MemPtr,
1764                                               const MemberPointerType *MPT) {
1765   assert(MPT->isMemberDataPointer());
1766   unsigned AS = Base->getType()->getPointerAddressSpace();
1767   llvm::Type *PType =
1768       CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1769   CGBuilderTy &Builder = CGF.Builder;
1770   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1771   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1772 
1773   // Extract the fields we need, regardless of model.  We'll apply them if we
1774   // have them.
1775   llvm::Value *FieldOffset = MemPtr;
1776   llvm::Value *VirtualBaseAdjustmentOffset = 0;
1777   llvm::Value *VBPtrOffset = 0;
1778   if (MemPtr->getType()->isStructTy()) {
1779     // We need to extract values.
1780     unsigned I = 0;
1781     FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1782     if (hasVBPtrOffsetField(Inheritance))
1783       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1784     if (hasVirtualBaseAdjustmentField(Inheritance))
1785       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1786   }
1787 
1788   if (VirtualBaseAdjustmentOffset) {
1789     Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1790                              VBPtrOffset);
1791   }
1792 
1793   // Cast to char*.
1794   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
1795 
1796   // Apply the offset, which we assume is non-null.
1797   llvm::Value *Addr =
1798     Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
1799 
1800   // Cast the address to the appropriate pointer type, adopting the address
1801   // space of the base pointer.
1802   return Builder.CreateBitCast(Addr, PType);
1803 }
1804 
1805 static MSInheritanceAttr::Spelling
1806 getInheritanceFromMemptr(const MemberPointerType *MPT) {
1807   return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
1808 }
1809 
1810 llvm::Value *
1811 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1812                                              const CastExpr *E,
1813                                              llvm::Value *Src) {
1814   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1815          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1816          E->getCastKind() == CK_ReinterpretMemberPointer);
1817 
1818   // Use constant emission if we can.
1819   if (isa<llvm::Constant>(Src))
1820     return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1821 
1822   // We may be adding or dropping fields from the member pointer, so we need
1823   // both types and the inheritance models of both records.
1824   const MemberPointerType *SrcTy =
1825     E->getSubExpr()->getType()->castAs<MemberPointerType>();
1826   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1827   bool IsFunc = SrcTy->isMemberFunctionPointer();
1828 
1829   // If the classes use the same null representation, reinterpret_cast is a nop.
1830   bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1831   if (IsReinterpret && IsFunc)
1832     return Src;
1833 
1834   CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
1835   CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
1836   if (IsReinterpret &&
1837       nullFieldOffsetIsZero(SrcRD) == nullFieldOffsetIsZero(DstRD))
1838     return Src;
1839 
1840   CGBuilderTy &Builder = CGF.Builder;
1841 
1842   // Branch past the conversion if Src is null.
1843   llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1844   llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1845 
1846   // C++ 5.2.10p9: The null member pointer value is converted to the null member
1847   //   pointer value of the destination type.
1848   if (IsReinterpret) {
1849     // For reinterpret casts, sema ensures that src and dst are both functions
1850     // or data and have the same size, which means the LLVM types should match.
1851     assert(Src->getType() == DstNull->getType());
1852     return Builder.CreateSelect(IsNotNull, Src, DstNull);
1853   }
1854 
1855   llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1856   llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1857   llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1858   Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1859   CGF.EmitBlock(ConvertBB);
1860 
1861   // Decompose src.
1862   llvm::Value *FirstField = Src;
1863   llvm::Value *NonVirtualBaseAdjustment = 0;
1864   llvm::Value *VirtualBaseAdjustmentOffset = 0;
1865   llvm::Value *VBPtrOffset = 0;
1866   MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
1867   if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1868     // We need to extract values.
1869     unsigned I = 0;
1870     FirstField = Builder.CreateExtractValue(Src, I++);
1871     if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1872       NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1873     if (hasVBPtrOffsetField(SrcInheritance))
1874       VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1875     if (hasVirtualBaseAdjustmentField(SrcInheritance))
1876       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1877   }
1878 
1879   // For data pointers, we adjust the field offset directly.  For functions, we
1880   // have a separate field.
1881   llvm::Constant *Adj = getMemberPointerAdjustment(E);
1882   if (Adj) {
1883     Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1884     llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1885     bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1886     if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
1887       NVAdjustField = getZeroInt();
1888     if (isDerivedToBase)
1889       NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1890     else
1891       NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1892   }
1893 
1894   // FIXME PR15713: Support conversions through virtually derived classes.
1895 
1896   // Recompose dst from the null struct and the adjusted fields from src.
1897   MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
1898   llvm::Value *Dst;
1899   if (hasOnlyOneField(IsFunc, DstInheritance)) {
1900     Dst = FirstField;
1901   } else {
1902     Dst = llvm::UndefValue::get(DstNull->getType());
1903     unsigned Idx = 0;
1904     Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1905     if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1906       Dst = Builder.CreateInsertValue(
1907         Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1908     if (hasVBPtrOffsetField(DstInheritance))
1909       Dst = Builder.CreateInsertValue(
1910         Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1911     if (hasVirtualBaseAdjustmentField(DstInheritance))
1912       Dst = Builder.CreateInsertValue(
1913         Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1914   }
1915   Builder.CreateBr(ContinueBB);
1916 
1917   // In the continuation, choose between DstNull and Dst.
1918   CGF.EmitBlock(ContinueBB);
1919   llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1920   Phi->addIncoming(DstNull, OriginalBB);
1921   Phi->addIncoming(Dst, ConvertBB);
1922   return Phi;
1923 }
1924 
1925 llvm::Constant *
1926 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1927                                              llvm::Constant *Src) {
1928   const MemberPointerType *SrcTy =
1929     E->getSubExpr()->getType()->castAs<MemberPointerType>();
1930   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1931 
1932   // If src is null, emit a new null for dst.  We can't return src because dst
1933   // might have a new representation.
1934   if (MemberPointerConstantIsNull(SrcTy, Src))
1935     return EmitNullMemberPointer(DstTy);
1936 
1937   // We don't need to do anything for reinterpret_casts of non-null member
1938   // pointers.  We should only get here when the two type representations have
1939   // the same size.
1940   if (E->getCastKind() == CK_ReinterpretMemberPointer)
1941     return Src;
1942 
1943   MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
1944   MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
1945 
1946   // Decompose src.
1947   llvm::Constant *FirstField = Src;
1948   llvm::Constant *NonVirtualBaseAdjustment = 0;
1949   llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1950   llvm::Constant *VBPtrOffset = 0;
1951   bool IsFunc = SrcTy->isMemberFunctionPointer();
1952   if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1953     // We need to extract values.
1954     unsigned I = 0;
1955     FirstField = Src->getAggregateElement(I++);
1956     if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1957       NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1958     if (hasVBPtrOffsetField(SrcInheritance))
1959       VBPtrOffset = Src->getAggregateElement(I++);
1960     if (hasVirtualBaseAdjustmentField(SrcInheritance))
1961       VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1962   }
1963 
1964   // For data pointers, we adjust the field offset directly.  For functions, we
1965   // have a separate field.
1966   llvm::Constant *Adj = getMemberPointerAdjustment(E);
1967   if (Adj) {
1968     Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1969     llvm::Constant *&NVAdjustField =
1970       IsFunc ? NonVirtualBaseAdjustment : FirstField;
1971     bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1972     if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
1973       NVAdjustField = getZeroInt();
1974     if (IsDerivedToBase)
1975       NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1976     else
1977       NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1978   }
1979 
1980   // FIXME PR15713: Support conversions through virtually derived classes.
1981 
1982   // Recompose dst from the null struct and the adjusted fields from src.
1983   if (hasOnlyOneField(IsFunc, DstInheritance))
1984     return FirstField;
1985 
1986   llvm::SmallVector<llvm::Constant *, 4> Fields;
1987   Fields.push_back(FirstField);
1988   if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1989     Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1990   if (hasVBPtrOffsetField(DstInheritance))
1991     Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1992   if (hasVirtualBaseAdjustmentField(DstInheritance))
1993     Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1994   return llvm::ConstantStruct::getAnon(Fields);
1995 }
1996 
1997 llvm::Value *
1998 MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1999                                                  llvm::Value *&This,
2000                                                  llvm::Value *MemPtr,
2001                                                  const MemberPointerType *MPT) {
2002   assert(MPT->isMemberFunctionPointer());
2003   const FunctionProtoType *FPT =
2004     MPT->getPointeeType()->castAs<FunctionProtoType>();
2005   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2006   llvm::FunctionType *FTy =
2007     CGM.getTypes().GetFunctionType(
2008       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2009   CGBuilderTy &Builder = CGF.Builder;
2010 
2011   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2012 
2013   // Extract the fields we need, regardless of model.  We'll apply them if we
2014   // have them.
2015   llvm::Value *FunctionPointer = MemPtr;
2016   llvm::Value *NonVirtualBaseAdjustment = NULL;
2017   llvm::Value *VirtualBaseAdjustmentOffset = NULL;
2018   llvm::Value *VBPtrOffset = NULL;
2019   if (MemPtr->getType()->isStructTy()) {
2020     // We need to extract values.
2021     unsigned I = 0;
2022     FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
2023     if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
2024       NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
2025     if (hasVBPtrOffsetField(Inheritance))
2026       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2027     if (hasVirtualBaseAdjustmentField(Inheritance))
2028       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2029   }
2030 
2031   if (VirtualBaseAdjustmentOffset) {
2032     This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
2033                              VBPtrOffset);
2034   }
2035 
2036   if (NonVirtualBaseAdjustment) {
2037     // Apply the adjustment and cast back to the original struct type.
2038     llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2039     Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2040     This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2041   }
2042 
2043   return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2044 }
2045 
2046 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
2047   return new MicrosoftCXXABI(CGM);
2048 }
2049