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