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