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