]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGClass.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGClass.cpp
1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with C++ code generation of classes
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CGBlocks.h"
15 #include "CGCXXABI.h"
16 #include "CGDebugInfo.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "TargetInfo.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/Basic/CodeGenOptions.h"
26 #include "clang/Basic/TargetBuiltins.h"
27 #include "clang/CodeGen/CGFunctionInfo.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/Transforms/Utils/SanitizerStats.h"
31
32 using namespace clang;
33 using namespace CodeGen;
34
35 /// Return the best known alignment for an unknown pointer to a
36 /// particular class.
37 CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
38   if (!RD->isCompleteDefinition())
39     return CharUnits::One(); // Hopefully won't be used anywhere.
40
41   auto &layout = getContext().getASTRecordLayout(RD);
42
43   // If the class is final, then we know that the pointer points to an
44   // object of that type and can use the full alignment.
45   if (RD->hasAttr<FinalAttr>()) {
46     return layout.getAlignment();
47
48   // Otherwise, we have to assume it could be a subclass.
49   } else {
50     return layout.getNonVirtualAlignment();
51   }
52 }
53
54 /// Return the best known alignment for a pointer to a virtual base,
55 /// given the alignment of a pointer to the derived class.
56 CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
57                                            const CXXRecordDecl *derivedClass,
58                                            const CXXRecordDecl *vbaseClass) {
59   // The basic idea here is that an underaligned derived pointer might
60   // indicate an underaligned base pointer.
61
62   assert(vbaseClass->isCompleteDefinition());
63   auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
64   CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
65
66   return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
67                                    expectedVBaseAlign);
68 }
69
70 CharUnits
71 CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
72                                          const CXXRecordDecl *baseDecl,
73                                          CharUnits expectedTargetAlign) {
74   // If the base is an incomplete type (which is, alas, possible with
75   // member pointers), be pessimistic.
76   if (!baseDecl->isCompleteDefinition())
77     return std::min(actualBaseAlign, expectedTargetAlign);
78
79   auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
80   CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
81
82   // If the class is properly aligned, assume the target offset is, too.
83   //
84   // This actually isn't necessarily the right thing to do --- if the
85   // class is a complete object, but it's only properly aligned for a
86   // base subobject, then the alignments of things relative to it are
87   // probably off as well.  (Note that this requires the alignment of
88   // the target to be greater than the NV alignment of the derived
89   // class.)
90   //
91   // However, our approach to this kind of under-alignment can only
92   // ever be best effort; after all, we're never going to propagate
93   // alignments through variables or parameters.  Note, in particular,
94   // that constructing a polymorphic type in an address that's less
95   // than pointer-aligned will generally trap in the constructor,
96   // unless we someday add some sort of attribute to change the
97   // assumed alignment of 'this'.  So our goal here is pretty much
98   // just to allow the user to explicitly say that a pointer is
99   // under-aligned and then safely access its fields and vtables.
100   if (actualBaseAlign >= expectedBaseAlign) {
101     return expectedTargetAlign;
102   }
103
104   // Otherwise, we might be offset by an arbitrary multiple of the
105   // actual alignment.  The correct adjustment is to take the min of
106   // the two alignments.
107   return std::min(actualBaseAlign, expectedTargetAlign);
108 }
109
110 Address CodeGenFunction::LoadCXXThisAddress() {
111   assert(CurFuncDecl && "loading 'this' without a func declaration?");
112   assert(isa<CXXMethodDecl>(CurFuncDecl));
113
114   // Lazily compute CXXThisAlignment.
115   if (CXXThisAlignment.isZero()) {
116     // Just use the best known alignment for the parent.
117     // TODO: if we're currently emitting a complete-object ctor/dtor,
118     // we can always use the complete-object alignment.
119     auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
120     CXXThisAlignment = CGM.getClassPointerAlignment(RD);
121   }
122
123   return Address(LoadCXXThis(), CXXThisAlignment);
124 }
125
126 /// Emit the address of a field using a member data pointer.
127 ///
128 /// \param E Only used for emergency diagnostics
129 Address
130 CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
131                                                  llvm::Value *memberPtr,
132                                       const MemberPointerType *memberPtrType,
133                                                  LValueBaseInfo *BaseInfo,
134                                                  TBAAAccessInfo *TBAAInfo) {
135   // Ask the ABI to compute the actual address.
136   llvm::Value *ptr =
137     CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
138                                                  memberPtr, memberPtrType);
139
140   QualType memberType = memberPtrType->getPointeeType();
141   CharUnits memberAlign = getNaturalTypeAlignment(memberType, BaseInfo,
142                                                   TBAAInfo);
143   memberAlign =
144     CGM.getDynamicOffsetAlignment(base.getAlignment(),
145                             memberPtrType->getClass()->getAsCXXRecordDecl(),
146                                   memberAlign);
147   return Address(ptr, memberAlign);
148 }
149
150 CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
151     const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
152     CastExpr::path_const_iterator End) {
153   CharUnits Offset = CharUnits::Zero();
154
155   const ASTContext &Context = getContext();
156   const CXXRecordDecl *RD = DerivedClass;
157
158   for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
159     const CXXBaseSpecifier *Base = *I;
160     assert(!Base->isVirtual() && "Should not see virtual bases here!");
161
162     // Get the layout.
163     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
164
165     const CXXRecordDecl *BaseDecl =
166       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
167
168     // Add the offset.
169     Offset += Layout.getBaseClassOffset(BaseDecl);
170
171     RD = BaseDecl;
172   }
173
174   return Offset;
175 }
176
177 llvm::Constant *
178 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
179                                    CastExpr::path_const_iterator PathBegin,
180                                    CastExpr::path_const_iterator PathEnd) {
181   assert(PathBegin != PathEnd && "Base path should not be empty!");
182
183   CharUnits Offset =
184       computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
185   if (Offset.isZero())
186     return nullptr;
187
188   llvm::Type *PtrDiffTy =
189   Types.ConvertType(getContext().getPointerDiffType());
190
191   return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
192 }
193
194 /// Gets the address of a direct base class within a complete object.
195 /// This should only be used for (1) non-virtual bases or (2) virtual bases
196 /// when the type is known to be complete (e.g. in complete destructors).
197 ///
198 /// The object pointed to by 'This' is assumed to be non-null.
199 Address
200 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
201                                                    const CXXRecordDecl *Derived,
202                                                    const CXXRecordDecl *Base,
203                                                    bool BaseIsVirtual) {
204   // 'this' must be a pointer (in some address space) to Derived.
205   assert(This.getElementType() == ConvertType(Derived));
206
207   // Compute the offset of the virtual base.
208   CharUnits Offset;
209   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
210   if (BaseIsVirtual)
211     Offset = Layout.getVBaseClassOffset(Base);
212   else
213     Offset = Layout.getBaseClassOffset(Base);
214
215   // Shift and cast down to the base type.
216   // TODO: for complete types, this should be possible with a GEP.
217   Address V = This;
218   if (!Offset.isZero()) {
219     V = Builder.CreateElementBitCast(V, Int8Ty);
220     V = Builder.CreateConstInBoundsByteGEP(V, Offset);
221   }
222   V = Builder.CreateElementBitCast(V, ConvertType(Base));
223
224   return V;
225 }
226
227 static Address
228 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
229                                 CharUnits nonVirtualOffset,
230                                 llvm::Value *virtualOffset,
231                                 const CXXRecordDecl *derivedClass,
232                                 const CXXRecordDecl *nearestVBase) {
233   // Assert that we have something to do.
234   assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
235
236   // Compute the offset from the static and dynamic components.
237   llvm::Value *baseOffset;
238   if (!nonVirtualOffset.isZero()) {
239     baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
240                                         nonVirtualOffset.getQuantity());
241     if (virtualOffset) {
242       baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
243     }
244   } else {
245     baseOffset = virtualOffset;
246   }
247
248   // Apply the base offset.
249   llvm::Value *ptr = addr.getPointer();
250   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
251   ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
252
253   // If we have a virtual component, the alignment of the result will
254   // be relative only to the known alignment of that vbase.
255   CharUnits alignment;
256   if (virtualOffset) {
257     assert(nearestVBase && "virtual offset without vbase?");
258     alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
259                                           derivedClass, nearestVBase);
260   } else {
261     alignment = addr.getAlignment();
262   }
263   alignment = alignment.alignmentAtOffset(nonVirtualOffset);
264
265   return Address(ptr, alignment);
266 }
267
268 Address CodeGenFunction::GetAddressOfBaseClass(
269     Address Value, const CXXRecordDecl *Derived,
270     CastExpr::path_const_iterator PathBegin,
271     CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
272     SourceLocation Loc) {
273   assert(PathBegin != PathEnd && "Base path should not be empty!");
274
275   CastExpr::path_const_iterator Start = PathBegin;
276   const CXXRecordDecl *VBase = nullptr;
277
278   // Sema has done some convenient canonicalization here: if the
279   // access path involved any virtual steps, the conversion path will
280   // *start* with a step down to the correct virtual base subobject,
281   // and hence will not require any further steps.
282   if ((*Start)->isVirtual()) {
283     VBase =
284       cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
285     ++Start;
286   }
287
288   // Compute the static offset of the ultimate destination within its
289   // allocating subobject (the virtual base, if there is one, or else
290   // the "complete" object that we see).
291   CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
292       VBase ? VBase : Derived, Start, PathEnd);
293
294   // If there's a virtual step, we can sometimes "devirtualize" it.
295   // For now, that's limited to when the derived type is final.
296   // TODO: "devirtualize" this for accesses to known-complete objects.
297   if (VBase && Derived->hasAttr<FinalAttr>()) {
298     const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
299     CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
300     NonVirtualOffset += vBaseOffset;
301     VBase = nullptr; // we no longer have a virtual step
302   }
303
304   // Get the base pointer type.
305   llvm::Type *BasePtrTy =
306     ConvertType((PathEnd[-1])->getType())->getPointerTo();
307
308   QualType DerivedTy = getContext().getRecordType(Derived);
309   CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
310
311   // If the static offset is zero and we don't have a virtual step,
312   // just do a bitcast; null checks are unnecessary.
313   if (NonVirtualOffset.isZero() && !VBase) {
314     if (sanitizePerformTypeCheck()) {
315       SanitizerSet SkippedChecks;
316       SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
317       EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
318                     DerivedTy, DerivedAlign, SkippedChecks);
319     }
320     return Builder.CreateBitCast(Value, BasePtrTy);
321   }
322
323   llvm::BasicBlock *origBB = nullptr;
324   llvm::BasicBlock *endBB = nullptr;
325
326   // Skip over the offset (and the vtable load) if we're supposed to
327   // null-check the pointer.
328   if (NullCheckValue) {
329     origBB = Builder.GetInsertBlock();
330     llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
331     endBB = createBasicBlock("cast.end");
332
333     llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
334     Builder.CreateCondBr(isNull, endBB, notNullBB);
335     EmitBlock(notNullBB);
336   }
337
338   if (sanitizePerformTypeCheck()) {
339     SanitizerSet SkippedChecks;
340     SkippedChecks.set(SanitizerKind::Null, true);
341     EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
342                   Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
343   }
344
345   // Compute the virtual offset.
346   llvm::Value *VirtualOffset = nullptr;
347   if (VBase) {
348     VirtualOffset =
349       CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
350   }
351
352   // Apply both offsets.
353   Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
354                                           VirtualOffset, Derived, VBase);
355
356   // Cast to the destination type.
357   Value = Builder.CreateBitCast(Value, BasePtrTy);
358
359   // Build a phi if we needed a null check.
360   if (NullCheckValue) {
361     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
362     Builder.CreateBr(endBB);
363     EmitBlock(endBB);
364
365     llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
366     PHI->addIncoming(Value.getPointer(), notNullBB);
367     PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
368     Value = Address(PHI, Value.getAlignment());
369   }
370
371   return Value;
372 }
373
374 Address
375 CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
376                                           const CXXRecordDecl *Derived,
377                                         CastExpr::path_const_iterator PathBegin,
378                                           CastExpr::path_const_iterator PathEnd,
379                                           bool NullCheckValue) {
380   assert(PathBegin != PathEnd && "Base path should not be empty!");
381
382   QualType DerivedTy =
383     getContext().getCanonicalType(getContext().getTagDeclType(Derived));
384   llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
385
386   llvm::Value *NonVirtualOffset =
387     CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
388
389   if (!NonVirtualOffset) {
390     // No offset, we can just cast back.
391     return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
392   }
393
394   llvm::BasicBlock *CastNull = nullptr;
395   llvm::BasicBlock *CastNotNull = nullptr;
396   llvm::BasicBlock *CastEnd = nullptr;
397
398   if (NullCheckValue) {
399     CastNull = createBasicBlock("cast.null");
400     CastNotNull = createBasicBlock("cast.notnull");
401     CastEnd = createBasicBlock("cast.end");
402
403     llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
404     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
405     EmitBlock(CastNotNull);
406   }
407
408   // Apply the offset.
409   llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
410   Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
411                                     "sub.ptr");
412
413   // Just cast.
414   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
415
416   // Produce a PHI if we had a null-check.
417   if (NullCheckValue) {
418     Builder.CreateBr(CastEnd);
419     EmitBlock(CastNull);
420     Builder.CreateBr(CastEnd);
421     EmitBlock(CastEnd);
422
423     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
424     PHI->addIncoming(Value, CastNotNull);
425     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
426     Value = PHI;
427   }
428
429   return Address(Value, CGM.getClassPointerAlignment(Derived));
430 }
431
432 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
433                                               bool ForVirtualBase,
434                                               bool Delegating) {
435   if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
436     // This constructor/destructor does not need a VTT parameter.
437     return nullptr;
438   }
439
440   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
441   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
442
443   llvm::Value *VTT;
444
445   uint64_t SubVTTIndex;
446
447   if (Delegating) {
448     // If this is a delegating constructor call, just load the VTT.
449     return LoadCXXVTT();
450   } else if (RD == Base) {
451     // If the record matches the base, this is the complete ctor/dtor
452     // variant calling the base variant in a class with virtual bases.
453     assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
454            "doing no-op VTT offset in base dtor/ctor?");
455     assert(!ForVirtualBase && "Can't have same class as virtual base!");
456     SubVTTIndex = 0;
457   } else {
458     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
459     CharUnits BaseOffset = ForVirtualBase ?
460       Layout.getVBaseClassOffset(Base) :
461       Layout.getBaseClassOffset(Base);
462
463     SubVTTIndex =
464       CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
465     assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
466   }
467
468   if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
469     // A VTT parameter was passed to the constructor, use it.
470     VTT = LoadCXXVTT();
471     VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
472   } else {
473     // We're the complete constructor, so get the VTT by name.
474     VTT = CGM.getVTables().GetAddrOfVTT(RD);
475     VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
476   }
477
478   return VTT;
479 }
480
481 namespace {
482   /// Call the destructor for a direct base class.
483   struct CallBaseDtor final : EHScopeStack::Cleanup {
484     const CXXRecordDecl *BaseClass;
485     bool BaseIsVirtual;
486     CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
487       : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
488
489     void Emit(CodeGenFunction &CGF, Flags flags) override {
490       const CXXRecordDecl *DerivedClass =
491         cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
492
493       const CXXDestructorDecl *D = BaseClass->getDestructor();
494       Address Addr =
495         CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
496                                                   DerivedClass, BaseClass,
497                                                   BaseIsVirtual);
498       CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
499                                 /*Delegating=*/false, Addr);
500     }
501   };
502
503   /// A visitor which checks whether an initializer uses 'this' in a
504   /// way which requires the vtable to be properly set.
505   struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
506     typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
507
508     bool UsesThis;
509
510     DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
511
512     // Black-list all explicit and implicit references to 'this'.
513     //
514     // Do we need to worry about external references to 'this' derived
515     // from arbitrary code?  If so, then anything which runs arbitrary
516     // external code might potentially access the vtable.
517     void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
518   };
519 } // end anonymous namespace
520
521 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
522   DynamicThisUseChecker Checker(C);
523   Checker.Visit(Init);
524   return Checker.UsesThis;
525 }
526
527 static void EmitBaseInitializer(CodeGenFunction &CGF,
528                                 const CXXRecordDecl *ClassDecl,
529                                 CXXCtorInitializer *BaseInit,
530                                 CXXCtorType CtorType) {
531   assert(BaseInit->isBaseInitializer() &&
532          "Must have base initializer!");
533
534   Address ThisPtr = CGF.LoadCXXThisAddress();
535
536   const Type *BaseType = BaseInit->getBaseClass();
537   CXXRecordDecl *BaseClassDecl =
538     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
539
540   bool isBaseVirtual = BaseInit->isBaseVirtual();
541
542   // The base constructor doesn't construct virtual bases.
543   if (CtorType == Ctor_Base && isBaseVirtual)
544     return;
545
546   // If the initializer for the base (other than the constructor
547   // itself) accesses 'this' in any way, we need to initialize the
548   // vtables.
549   if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
550     CGF.InitializeVTablePointers(ClassDecl);
551
552   // We can pretend to be a complete class because it only matters for
553   // virtual bases, and we only do virtual bases for complete ctors.
554   Address V =
555     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
556                                               BaseClassDecl,
557                                               isBaseVirtual);
558   AggValueSlot AggSlot =
559       AggValueSlot::forAddr(
560           V, Qualifiers(),
561           AggValueSlot::IsDestructed,
562           AggValueSlot::DoesNotNeedGCBarriers,
563           AggValueSlot::IsNotAliased,
564           CGF.overlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
565
566   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
567
568   if (CGF.CGM.getLangOpts().Exceptions &&
569       !BaseClassDecl->hasTrivialDestructor())
570     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
571                                           isBaseVirtual);
572 }
573
574 static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
575   auto *CD = dyn_cast<CXXConstructorDecl>(D);
576   if (!(CD && CD->isCopyOrMoveConstructor()) &&
577       !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
578     return false;
579
580   // We can emit a memcpy for a trivial copy or move constructor/assignment.
581   if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
582     return true;
583
584   // We *must* emit a memcpy for a defaulted union copy or move op.
585   if (D->getParent()->isUnion() && D->isDefaulted())
586     return true;
587
588   return false;
589 }
590
591 static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
592                                                 CXXCtorInitializer *MemberInit,
593                                                 LValue &LHS) {
594   FieldDecl *Field = MemberInit->getAnyMember();
595   if (MemberInit->isIndirectMemberInitializer()) {
596     // If we are initializing an anonymous union field, drill down to the field.
597     IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
598     for (const auto *I : IndirectField->chain())
599       LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
600   } else {
601     LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
602   }
603 }
604
605 static void EmitMemberInitializer(CodeGenFunction &CGF,
606                                   const CXXRecordDecl *ClassDecl,
607                                   CXXCtorInitializer *MemberInit,
608                                   const CXXConstructorDecl *Constructor,
609                                   FunctionArgList &Args) {
610   ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
611   assert(MemberInit->isAnyMemberInitializer() &&
612          "Must have member initializer!");
613   assert(MemberInit->getInit() && "Must have initializer!");
614
615   // non-static data member initializers.
616   FieldDecl *Field = MemberInit->getAnyMember();
617   QualType FieldType = Field->getType();
618
619   llvm::Value *ThisPtr = CGF.LoadCXXThis();
620   QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
621   LValue LHS;
622
623   // If a base constructor is being emitted, create an LValue that has the
624   // non-virtual alignment.
625   if (CGF.CurGD.getCtorType() == Ctor_Base)
626     LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
627   else
628     LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
629
630   EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
631
632   // Special case: if we are in a copy or move constructor, and we are copying
633   // an array of PODs or classes with trivial copy constructors, ignore the
634   // AST and perform the copy we know is equivalent.
635   // FIXME: This is hacky at best... if we had a bit more explicit information
636   // in the AST, we could generalize it more easily.
637   const ConstantArrayType *Array
638     = CGF.getContext().getAsConstantArrayType(FieldType);
639   if (Array && Constructor->isDefaulted() &&
640       Constructor->isCopyOrMoveConstructor()) {
641     QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
642     CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
643     if (BaseElementTy.isPODType(CGF.getContext()) ||
644         (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
645       unsigned SrcArgIndex =
646           CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
647       llvm::Value *SrcPtr
648         = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
649       LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
650       LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
651
652       // Copy the aggregate.
653       CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.overlapForFieldInit(Field),
654                             LHS.isVolatileQualified());
655       // Ensure that we destroy the objects if an exception is thrown later in
656       // the constructor.
657       QualType::DestructionKind dtorKind = FieldType.isDestructedType();
658       if (CGF.needsEHCleanup(dtorKind))
659         CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
660       return;
661     }
662   }
663
664   CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
665 }
666
667 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
668                                               Expr *Init) {
669   QualType FieldType = Field->getType();
670   switch (getEvaluationKind(FieldType)) {
671   case TEK_Scalar:
672     if (LHS.isSimple()) {
673       EmitExprAsInit(Init, Field, LHS, false);
674     } else {
675       RValue RHS = RValue::get(EmitScalarExpr(Init));
676       EmitStoreThroughLValue(RHS, LHS);
677     }
678     break;
679   case TEK_Complex:
680     EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
681     break;
682   case TEK_Aggregate: {
683     AggValueSlot Slot =
684         AggValueSlot::forLValue(
685             LHS,
686             AggValueSlot::IsDestructed,
687             AggValueSlot::DoesNotNeedGCBarriers,
688             AggValueSlot::IsNotAliased,
689             overlapForFieldInit(Field),
690             AggValueSlot::IsNotZeroed,
691             // Checks are made by the code that calls constructor.
692             AggValueSlot::IsSanitizerChecked);
693     EmitAggExpr(Init, Slot);
694     break;
695   }
696   }
697
698   // Ensure that we destroy this object if an exception is thrown
699   // later in the constructor.
700   QualType::DestructionKind dtorKind = FieldType.isDestructedType();
701   if (needsEHCleanup(dtorKind))
702     pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
703 }
704
705 /// Checks whether the given constructor is a valid subject for the
706 /// complete-to-base constructor delegation optimization, i.e.
707 /// emitting the complete constructor as a simple call to the base
708 /// constructor.
709 bool CodeGenFunction::IsConstructorDelegationValid(
710     const CXXConstructorDecl *Ctor) {
711
712   // Currently we disable the optimization for classes with virtual
713   // bases because (1) the addresses of parameter variables need to be
714   // consistent across all initializers but (2) the delegate function
715   // call necessarily creates a second copy of the parameter variable.
716   //
717   // The limiting example (purely theoretical AFAIK):
718   //   struct A { A(int &c) { c++; } };
719   //   struct B : virtual A {
720   //     B(int count) : A(count) { printf("%d\n", count); }
721   //   };
722   // ...although even this example could in principle be emitted as a
723   // delegation since the address of the parameter doesn't escape.
724   if (Ctor->getParent()->getNumVBases()) {
725     // TODO: white-list trivial vbase initializers.  This case wouldn't
726     // be subject to the restrictions below.
727
728     // TODO: white-list cases where:
729     //  - there are no non-reference parameters to the constructor
730     //  - the initializers don't access any non-reference parameters
731     //  - the initializers don't take the address of non-reference
732     //    parameters
733     //  - etc.
734     // If we ever add any of the above cases, remember that:
735     //  - function-try-blocks will always blacklist this optimization
736     //  - we need to perform the constructor prologue and cleanup in
737     //    EmitConstructorBody.
738
739     return false;
740   }
741
742   // We also disable the optimization for variadic functions because
743   // it's impossible to "re-pass" varargs.
744   if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
745     return false;
746
747   // FIXME: Decide if we can do a delegation of a delegating constructor.
748   if (Ctor->isDelegatingConstructor())
749     return false;
750
751   return true;
752 }
753
754 // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
755 // to poison the extra field paddings inserted under
756 // -fsanitize-address-field-padding=1|2.
757 void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
758   ASTContext &Context = getContext();
759   const CXXRecordDecl *ClassDecl =
760       Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
761                : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
762   if (!ClassDecl->mayInsertExtraPadding()) return;
763
764   struct SizeAndOffset {
765     uint64_t Size;
766     uint64_t Offset;
767   };
768
769   unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
770   const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
771
772   // Populate sizes and offsets of fields.
773   SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
774   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
775     SSV[i].Offset =
776         Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
777
778   size_t NumFields = 0;
779   for (const auto *Field : ClassDecl->fields()) {
780     const FieldDecl *D = Field;
781     std::pair<CharUnits, CharUnits> FieldInfo =
782         Context.getTypeInfoInChars(D->getType());
783     CharUnits FieldSize = FieldInfo.first;
784     assert(NumFields < SSV.size());
785     SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
786     NumFields++;
787   }
788   assert(NumFields == SSV.size());
789   if (SSV.size() <= 1) return;
790
791   // We will insert calls to __asan_* run-time functions.
792   // LLVM AddressSanitizer pass may decide to inline them later.
793   llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
794   llvm::FunctionType *FTy =
795       llvm::FunctionType::get(CGM.VoidTy, Args, false);
796   llvm::Constant *F = CGM.CreateRuntimeFunction(
797       FTy, Prologue ? "__asan_poison_intra_object_redzone"
798                     : "__asan_unpoison_intra_object_redzone");
799
800   llvm::Value *ThisPtr = LoadCXXThis();
801   ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
802   uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
803   // For each field check if it has sufficient padding,
804   // if so (un)poison it with a call.
805   for (size_t i = 0; i < SSV.size(); i++) {
806     uint64_t AsanAlignment = 8;
807     uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
808     uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
809     uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
810     if (PoisonSize < AsanAlignment || !SSV[i].Size ||
811         (NextField % AsanAlignment) != 0)
812       continue;
813     Builder.CreateCall(
814         F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
815             Builder.getIntN(PtrSize, PoisonSize)});
816   }
817 }
818
819 /// EmitConstructorBody - Emits the body of the current constructor.
820 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
821   EmitAsanPrologueOrEpilogue(true);
822   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
823   CXXCtorType CtorType = CurGD.getCtorType();
824
825   assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
826           CtorType == Ctor_Complete) &&
827          "can only generate complete ctor for this ABI");
828
829   // Before we go any further, try the complete->base constructor
830   // delegation optimization.
831   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
832       CGM.getTarget().getCXXABI().hasConstructorVariants()) {
833     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
834     return;
835   }
836
837   const FunctionDecl *Definition = nullptr;
838   Stmt *Body = Ctor->getBody(Definition);
839   assert(Definition == Ctor && "emitting wrong constructor body");
840
841   // Enter the function-try-block before the constructor prologue if
842   // applicable.
843   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
844   if (IsTryBody)
845     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
846
847   incrementProfileCounter(Body);
848
849   RunCleanupsScope RunCleanups(*this);
850
851   // TODO: in restricted cases, we can emit the vbase initializers of
852   // a complete ctor and then delegate to the base ctor.
853
854   // Emit the constructor prologue, i.e. the base and member
855   // initializers.
856   EmitCtorPrologue(Ctor, CtorType, Args);
857
858   // Emit the body of the statement.
859   if (IsTryBody)
860     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
861   else if (Body)
862     EmitStmt(Body);
863
864   // Emit any cleanup blocks associated with the member or base
865   // initializers, which includes (along the exceptional path) the
866   // destructors for those members and bases that were fully
867   // constructed.
868   RunCleanups.ForceCleanup();
869
870   if (IsTryBody)
871     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
872 }
873
874 namespace {
875   /// RAII object to indicate that codegen is copying the value representation
876   /// instead of the object representation. Useful when copying a struct or
877   /// class which has uninitialized members and we're only performing
878   /// lvalue-to-rvalue conversion on the object but not its members.
879   class CopyingValueRepresentation {
880   public:
881     explicit CopyingValueRepresentation(CodeGenFunction &CGF)
882         : CGF(CGF), OldSanOpts(CGF.SanOpts) {
883       CGF.SanOpts.set(SanitizerKind::Bool, false);
884       CGF.SanOpts.set(SanitizerKind::Enum, false);
885     }
886     ~CopyingValueRepresentation() {
887       CGF.SanOpts = OldSanOpts;
888     }
889   private:
890     CodeGenFunction &CGF;
891     SanitizerSet OldSanOpts;
892   };
893 } // end anonymous namespace
894
895 namespace {
896   class FieldMemcpyizer {
897   public:
898     FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
899                     const VarDecl *SrcRec)
900       : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
901         RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
902         FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
903         LastFieldOffset(0), LastAddedFieldIndex(0) {}
904
905     bool isMemcpyableField(FieldDecl *F) const {
906       // Never memcpy fields when we are adding poisoned paddings.
907       if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
908         return false;
909       Qualifiers Qual = F->getType().getQualifiers();
910       if (Qual.hasVolatile() || Qual.hasObjCLifetime())
911         return false;
912       return true;
913     }
914
915     void addMemcpyableField(FieldDecl *F) {
916       if (!FirstField)
917         addInitialField(F);
918       else
919         addNextField(F);
920     }
921
922     CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
923       ASTContext &Ctx = CGF.getContext();
924       unsigned LastFieldSize =
925           LastField->isBitField()
926               ? LastField->getBitWidthValue(Ctx)
927               : Ctx.toBits(
928                     Ctx.getTypeInfoDataSizeInChars(LastField->getType()).first);
929       uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
930                                 FirstByteOffset + Ctx.getCharWidth() - 1;
931       CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
932       return MemcpySize;
933     }
934
935     void emitMemcpy() {
936       // Give the subclass a chance to bail out if it feels the memcpy isn't
937       // worth it (e.g. Hasn't aggregated enough data).
938       if (!FirstField) {
939         return;
940       }
941
942       uint64_t FirstByteOffset;
943       if (FirstField->isBitField()) {
944         const CGRecordLayout &RL =
945           CGF.getTypes().getCGRecordLayout(FirstField->getParent());
946         const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
947         // FirstFieldOffset is not appropriate for bitfields,
948         // we need to use the storage offset instead.
949         FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
950       } else {
951         FirstByteOffset = FirstFieldOffset;
952       }
953
954       CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
955       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
956       Address ThisPtr = CGF.LoadCXXThisAddress();
957       LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
958       LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
959       llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
960       LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
961       LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
962
963       emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
964                    Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
965                    MemcpySize);
966       reset();
967     }
968
969     void reset() {
970       FirstField = nullptr;
971     }
972
973   protected:
974     CodeGenFunction &CGF;
975     const CXXRecordDecl *ClassDecl;
976
977   private:
978     void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
979       llvm::PointerType *DPT = DestPtr.getType();
980       llvm::Type *DBP =
981         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
982       DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
983
984       llvm::PointerType *SPT = SrcPtr.getType();
985       llvm::Type *SBP =
986         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
987       SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
988
989       CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
990     }
991
992     void addInitialField(FieldDecl *F) {
993       FirstField = F;
994       LastField = F;
995       FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
996       LastFieldOffset = FirstFieldOffset;
997       LastAddedFieldIndex = F->getFieldIndex();
998     }
999
1000     void addNextField(FieldDecl *F) {
1001       // For the most part, the following invariant will hold:
1002       //   F->getFieldIndex() == LastAddedFieldIndex + 1
1003       // The one exception is that Sema won't add a copy-initializer for an
1004       // unnamed bitfield, which will show up here as a gap in the sequence.
1005       assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
1006              "Cannot aggregate fields out of order.");
1007       LastAddedFieldIndex = F->getFieldIndex();
1008
1009       // The 'first' and 'last' fields are chosen by offset, rather than field
1010       // index. This allows the code to support bitfields, as well as regular
1011       // fields.
1012       uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
1013       if (FOffset < FirstFieldOffset) {
1014         FirstField = F;
1015         FirstFieldOffset = FOffset;
1016       } else if (FOffset > LastFieldOffset) {
1017         LastField = F;
1018         LastFieldOffset = FOffset;
1019       }
1020     }
1021
1022     const VarDecl *SrcRec;
1023     const ASTRecordLayout &RecLayout;
1024     FieldDecl *FirstField;
1025     FieldDecl *LastField;
1026     uint64_t FirstFieldOffset, LastFieldOffset;
1027     unsigned LastAddedFieldIndex;
1028   };
1029
1030   class ConstructorMemcpyizer : public FieldMemcpyizer {
1031   private:
1032     /// Get source argument for copy constructor. Returns null if not a copy
1033     /// constructor.
1034     static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1035                                                const CXXConstructorDecl *CD,
1036                                                FunctionArgList &Args) {
1037       if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1038         return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1039       return nullptr;
1040     }
1041
1042     // Returns true if a CXXCtorInitializer represents a member initialization
1043     // that can be rolled into a memcpy.
1044     bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1045       if (!MemcpyableCtor)
1046         return false;
1047       FieldDecl *Field = MemberInit->getMember();
1048       assert(Field && "No field for member init.");
1049       QualType FieldType = Field->getType();
1050       CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1051
1052       // Bail out on non-memcpyable, not-trivially-copyable members.
1053       if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
1054           !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1055             FieldType->isReferenceType()))
1056         return false;
1057
1058       // Bail out on volatile fields.
1059       if (!isMemcpyableField(Field))
1060         return false;
1061
1062       // Otherwise we're good.
1063       return true;
1064     }
1065
1066   public:
1067     ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1068                           FunctionArgList &Args)
1069       : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
1070         ConstructorDecl(CD),
1071         MemcpyableCtor(CD->isDefaulted() &&
1072                        CD->isCopyOrMoveConstructor() &&
1073                        CGF.getLangOpts().getGC() == LangOptions::NonGC),
1074         Args(Args) { }
1075
1076     void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1077       if (isMemberInitMemcpyable(MemberInit)) {
1078         AggregatedInits.push_back(MemberInit);
1079         addMemcpyableField(MemberInit->getMember());
1080       } else {
1081         emitAggregatedInits();
1082         EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1083                               ConstructorDecl, Args);
1084       }
1085     }
1086
1087     void emitAggregatedInits() {
1088       if (AggregatedInits.size() <= 1) {
1089         // This memcpy is too small to be worthwhile. Fall back on default
1090         // codegen.
1091         if (!AggregatedInits.empty()) {
1092           CopyingValueRepresentation CVR(CGF);
1093           EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1094                                 AggregatedInits[0], ConstructorDecl, Args);
1095           AggregatedInits.clear();
1096         }
1097         reset();
1098         return;
1099       }
1100
1101       pushEHDestructors();
1102       emitMemcpy();
1103       AggregatedInits.clear();
1104     }
1105
1106     void pushEHDestructors() {
1107       Address ThisPtr = CGF.LoadCXXThisAddress();
1108       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1109       LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
1110
1111       for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1112         CXXCtorInitializer *MemberInit = AggregatedInits[i];
1113         QualType FieldType = MemberInit->getAnyMember()->getType();
1114         QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1115         if (!CGF.needsEHCleanup(dtorKind))
1116           continue;
1117         LValue FieldLHS = LHS;
1118         EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1119         CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
1120       }
1121     }
1122
1123     void finish() {
1124       emitAggregatedInits();
1125     }
1126
1127   private:
1128     const CXXConstructorDecl *ConstructorDecl;
1129     bool MemcpyableCtor;
1130     FunctionArgList &Args;
1131     SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1132   };
1133
1134   class AssignmentMemcpyizer : public FieldMemcpyizer {
1135   private:
1136     // Returns the memcpyable field copied by the given statement, if one
1137     // exists. Otherwise returns null.
1138     FieldDecl *getMemcpyableField(Stmt *S) {
1139       if (!AssignmentsMemcpyable)
1140         return nullptr;
1141       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1142         // Recognise trivial assignments.
1143         if (BO->getOpcode() != BO_Assign)
1144           return nullptr;
1145         MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1146         if (!ME)
1147           return nullptr;
1148         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1149         if (!Field || !isMemcpyableField(Field))
1150           return nullptr;
1151         Stmt *RHS = BO->getRHS();
1152         if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1153           RHS = EC->getSubExpr();
1154         if (!RHS)
1155           return nullptr;
1156         if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1157           if (ME2->getMemberDecl() == Field)
1158             return Field;
1159         }
1160         return nullptr;
1161       } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1162         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1163         if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
1164           return nullptr;
1165         MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1166         if (!IOA)
1167           return nullptr;
1168         FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1169         if (!Field || !isMemcpyableField(Field))
1170           return nullptr;
1171         MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1172         if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1173           return nullptr;
1174         return Field;
1175       } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1176         FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1177         if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1178           return nullptr;
1179         Expr *DstPtr = CE->getArg(0);
1180         if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1181           DstPtr = DC->getSubExpr();
1182         UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1183         if (!DUO || DUO->getOpcode() != UO_AddrOf)
1184           return nullptr;
1185         MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1186         if (!ME)
1187           return nullptr;
1188         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1189         if (!Field || !isMemcpyableField(Field))
1190           return nullptr;
1191         Expr *SrcPtr = CE->getArg(1);
1192         if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1193           SrcPtr = SC->getSubExpr();
1194         UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1195         if (!SUO || SUO->getOpcode() != UO_AddrOf)
1196           return nullptr;
1197         MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1198         if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1199           return nullptr;
1200         return Field;
1201       }
1202
1203       return nullptr;
1204     }
1205
1206     bool AssignmentsMemcpyable;
1207     SmallVector<Stmt*, 16> AggregatedStmts;
1208
1209   public:
1210     AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1211                          FunctionArgList &Args)
1212       : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1213         AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1214       assert(Args.size() == 2);
1215     }
1216
1217     void emitAssignment(Stmt *S) {
1218       FieldDecl *F = getMemcpyableField(S);
1219       if (F) {
1220         addMemcpyableField(F);
1221         AggregatedStmts.push_back(S);
1222       } else {
1223         emitAggregatedStmts();
1224         CGF.EmitStmt(S);
1225       }
1226     }
1227
1228     void emitAggregatedStmts() {
1229       if (AggregatedStmts.size() <= 1) {
1230         if (!AggregatedStmts.empty()) {
1231           CopyingValueRepresentation CVR(CGF);
1232           CGF.EmitStmt(AggregatedStmts[0]);
1233         }
1234         reset();
1235       }
1236
1237       emitMemcpy();
1238       AggregatedStmts.clear();
1239     }
1240
1241     void finish() {
1242       emitAggregatedStmts();
1243     }
1244   };
1245 } // end anonymous namespace
1246
1247 static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1248   const Type *BaseType = BaseInit->getBaseClass();
1249   const auto *BaseClassDecl =
1250           cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1251   return BaseClassDecl->isDynamicClass();
1252 }
1253
1254 /// EmitCtorPrologue - This routine generates necessary code to initialize
1255 /// base classes and non-static data members belonging to this constructor.
1256 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1257                                        CXXCtorType CtorType,
1258                                        FunctionArgList &Args) {
1259   if (CD->isDelegatingConstructor())
1260     return EmitDelegatingCXXConstructorCall(CD, Args);
1261
1262   const CXXRecordDecl *ClassDecl = CD->getParent();
1263
1264   CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1265                                           E = CD->init_end();
1266
1267   llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1268   if (ClassDecl->getNumVBases() &&
1269       !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1270     // The ABIs that don't have constructor variants need to put a branch
1271     // before the virtual base initialization code.
1272     BaseCtorContinueBB =
1273       CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1274     assert(BaseCtorContinueBB);
1275   }
1276
1277   llvm::Value *const OldThis = CXXThisValue;
1278   // Virtual base initializers first.
1279   for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1280     if (CGM.getCodeGenOpts().StrictVTablePointers &&
1281         CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1282         isInitializerOfDynamicClass(*B))
1283       CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1284     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1285   }
1286
1287   if (BaseCtorContinueBB) {
1288     // Complete object handler should continue to the remaining initializers.
1289     Builder.CreateBr(BaseCtorContinueBB);
1290     EmitBlock(BaseCtorContinueBB);
1291   }
1292
1293   // Then, non-virtual base initializers.
1294   for (; B != E && (*B)->isBaseInitializer(); B++) {
1295     assert(!(*B)->isBaseVirtual());
1296
1297     if (CGM.getCodeGenOpts().StrictVTablePointers &&
1298         CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1299         isInitializerOfDynamicClass(*B))
1300       CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1301     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1302   }
1303
1304   CXXThisValue = OldThis;
1305
1306   InitializeVTablePointers(ClassDecl);
1307
1308   // And finally, initialize class members.
1309   FieldConstructionScope FCS(*this, LoadCXXThisAddress());
1310   ConstructorMemcpyizer CM(*this, CD, Args);
1311   for (; B != E; B++) {
1312     CXXCtorInitializer *Member = (*B);
1313     assert(!Member->isBaseInitializer());
1314     assert(Member->isAnyMemberInitializer() &&
1315            "Delegating initializer on non-delegating constructor");
1316     CM.addMemberInitializer(Member);
1317   }
1318   CM.finish();
1319 }
1320
1321 static bool
1322 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1323
1324 static bool
1325 HasTrivialDestructorBody(ASTContext &Context,
1326                          const CXXRecordDecl *BaseClassDecl,
1327                          const CXXRecordDecl *MostDerivedClassDecl)
1328 {
1329   // If the destructor is trivial we don't have to check anything else.
1330   if (BaseClassDecl->hasTrivialDestructor())
1331     return true;
1332
1333   if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1334     return false;
1335
1336   // Check fields.
1337   for (const auto *Field : BaseClassDecl->fields())
1338     if (!FieldHasTrivialDestructorBody(Context, Field))
1339       return false;
1340
1341   // Check non-virtual bases.
1342   for (const auto &I : BaseClassDecl->bases()) {
1343     if (I.isVirtual())
1344       continue;
1345
1346     const CXXRecordDecl *NonVirtualBase =
1347       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1348     if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1349                                   MostDerivedClassDecl))
1350       return false;
1351   }
1352
1353   if (BaseClassDecl == MostDerivedClassDecl) {
1354     // Check virtual bases.
1355     for (const auto &I : BaseClassDecl->vbases()) {
1356       const CXXRecordDecl *VirtualBase =
1357         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1358       if (!HasTrivialDestructorBody(Context, VirtualBase,
1359                                     MostDerivedClassDecl))
1360         return false;
1361     }
1362   }
1363
1364   return true;
1365 }
1366
1367 static bool
1368 FieldHasTrivialDestructorBody(ASTContext &Context,
1369                                           const FieldDecl *Field)
1370 {
1371   QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1372
1373   const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1374   if (!RT)
1375     return true;
1376
1377   CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1378
1379   // The destructor for an implicit anonymous union member is never invoked.
1380   if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1381     return false;
1382
1383   return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1384 }
1385
1386 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1387 /// any vtable pointers before calling this destructor.
1388 static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
1389                                                const CXXDestructorDecl *Dtor) {
1390   const CXXRecordDecl *ClassDecl = Dtor->getParent();
1391   if (!ClassDecl->isDynamicClass())
1392     return true;
1393
1394   if (!Dtor->hasTrivialBody())
1395     return false;
1396
1397   // Check the fields.
1398   for (const auto *Field : ClassDecl->fields())
1399     if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
1400       return false;
1401
1402   return true;
1403 }
1404
1405 /// EmitDestructorBody - Emits the body of the current destructor.
1406 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1407   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1408   CXXDtorType DtorType = CurGD.getDtorType();
1409
1410   // For an abstract class, non-base destructors are never used (and can't
1411   // be emitted in general, because vbase dtors may not have been validated
1412   // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1413   // in fact emit references to them from other compilations, so emit them
1414   // as functions containing a trap instruction.
1415   if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1416     llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1417     TrapCall->setDoesNotReturn();
1418     TrapCall->setDoesNotThrow();
1419     Builder.CreateUnreachable();
1420     Builder.ClearInsertionPoint();
1421     return;
1422   }
1423
1424   Stmt *Body = Dtor->getBody();
1425   if (Body)
1426     incrementProfileCounter(Body);
1427
1428   // The call to operator delete in a deleting destructor happens
1429   // outside of the function-try-block, which means it's always
1430   // possible to delegate the destructor body to the complete
1431   // destructor.  Do so.
1432   if (DtorType == Dtor_Deleting) {
1433     RunCleanupsScope DtorEpilogue(*this);
1434     EnterDtorCleanups(Dtor, Dtor_Deleting);
1435     if (HaveInsertPoint())
1436       EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1437                             /*Delegating=*/false, LoadCXXThisAddress());
1438     return;
1439   }
1440
1441   // If the body is a function-try-block, enter the try before
1442   // anything else.
1443   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1444   if (isTryBody)
1445     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1446   EmitAsanPrologueOrEpilogue(false);
1447
1448   // Enter the epilogue cleanups.
1449   RunCleanupsScope DtorEpilogue(*this);
1450
1451   // If this is the complete variant, just invoke the base variant;
1452   // the epilogue will destruct the virtual bases.  But we can't do
1453   // this optimization if the body is a function-try-block, because
1454   // we'd introduce *two* handler blocks.  In the Microsoft ABI, we
1455   // always delegate because we might not have a definition in this TU.
1456   switch (DtorType) {
1457   case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
1458   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1459
1460   case Dtor_Complete:
1461     assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1462            "can't emit a dtor without a body for non-Microsoft ABIs");
1463
1464     // Enter the cleanup scopes for virtual bases.
1465     EnterDtorCleanups(Dtor, Dtor_Complete);
1466
1467     if (!isTryBody) {
1468       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1469                             /*Delegating=*/false, LoadCXXThisAddress());
1470       break;
1471     }
1472
1473     // Fallthrough: act like we're in the base variant.
1474     LLVM_FALLTHROUGH;
1475
1476   case Dtor_Base:
1477     assert(Body);
1478
1479     // Enter the cleanup scopes for fields and non-virtual bases.
1480     EnterDtorCleanups(Dtor, Dtor_Base);
1481
1482     // Initialize the vtable pointers before entering the body.
1483     if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1484       // Insert the llvm.launder.invariant.group intrinsic before initializing
1485       // the vptrs to cancel any previous assumptions we might have made.
1486       if (CGM.getCodeGenOpts().StrictVTablePointers &&
1487           CGM.getCodeGenOpts().OptimizationLevel > 0)
1488         CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
1489       InitializeVTablePointers(Dtor->getParent());
1490     }
1491
1492     if (isTryBody)
1493       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1494     else if (Body)
1495       EmitStmt(Body);
1496     else {
1497       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1498       // nothing to do besides what's in the epilogue
1499     }
1500     // -fapple-kext must inline any call to this dtor into
1501     // the caller's body.
1502     if (getLangOpts().AppleKext)
1503       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1504
1505     break;
1506   }
1507
1508   // Jump out through the epilogue cleanups.
1509   DtorEpilogue.ForceCleanup();
1510
1511   // Exit the try if applicable.
1512   if (isTryBody)
1513     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1514 }
1515
1516 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1517   const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1518   const Stmt *RootS = AssignOp->getBody();
1519   assert(isa<CompoundStmt>(RootS) &&
1520          "Body of an implicit assignment operator should be compound stmt.");
1521   const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1522
1523   LexicalScope Scope(*this, RootCS->getSourceRange());
1524
1525   incrementProfileCounter(RootCS);
1526   AssignmentMemcpyizer AM(*this, AssignOp, Args);
1527   for (auto *I : RootCS->body())
1528     AM.emitAssignment(I);
1529   AM.finish();
1530 }
1531
1532 namespace {
1533   llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
1534                                      const CXXDestructorDecl *DD) {
1535     if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
1536       return CGF.EmitScalarExpr(ThisArg);
1537     return CGF.LoadCXXThis();
1538   }
1539
1540   /// Call the operator delete associated with the current destructor.
1541   struct CallDtorDelete final : EHScopeStack::Cleanup {
1542     CallDtorDelete() {}
1543
1544     void Emit(CodeGenFunction &CGF, Flags flags) override {
1545       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1546       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1547       CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1548                          LoadThisForDtorDelete(CGF, Dtor),
1549                          CGF.getContext().getTagDeclType(ClassDecl));
1550     }
1551   };
1552
1553   void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
1554                                      llvm::Value *ShouldDeleteCondition,
1555                                      bool ReturnAfterDelete) {
1556     llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1557     llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1558     llvm::Value *ShouldCallDelete
1559       = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1560     CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1561
1562     CGF.EmitBlock(callDeleteBB);
1563     const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1564     const CXXRecordDecl *ClassDecl = Dtor->getParent();
1565     CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
1566                        LoadThisForDtorDelete(CGF, Dtor),
1567                        CGF.getContext().getTagDeclType(ClassDecl));
1568     assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
1569                ReturnAfterDelete &&
1570            "unexpected value for ReturnAfterDelete");
1571     if (ReturnAfterDelete)
1572       CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
1573     else
1574       CGF.Builder.CreateBr(continueBB);
1575
1576     CGF.EmitBlock(continueBB);
1577   }
1578
1579   struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
1580     llvm::Value *ShouldDeleteCondition;
1581
1582   public:
1583     CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1584         : ShouldDeleteCondition(ShouldDeleteCondition) {
1585       assert(ShouldDeleteCondition != nullptr);
1586     }
1587
1588     void Emit(CodeGenFunction &CGF, Flags flags) override {
1589       EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
1590                                     /*ReturnAfterDelete*/false);
1591     }
1592   };
1593
1594   class DestroyField  final : public EHScopeStack::Cleanup {
1595     const FieldDecl *field;
1596     CodeGenFunction::Destroyer *destroyer;
1597     bool useEHCleanupForArray;
1598
1599   public:
1600     DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1601                  bool useEHCleanupForArray)
1602         : field(field), destroyer(destroyer),
1603           useEHCleanupForArray(useEHCleanupForArray) {}
1604
1605     void Emit(CodeGenFunction &CGF, Flags flags) override {
1606       // Find the address of the field.
1607       Address thisValue = CGF.LoadCXXThisAddress();
1608       QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1609       LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1610       LValue LV = CGF.EmitLValueForField(ThisLV, field);
1611       assert(LV.isSimple());
1612
1613       CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1614                       flags.isForNormalCleanup() && useEHCleanupForArray);
1615     }
1616   };
1617
1618  static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1619              CharUnits::QuantityType PoisonSize) {
1620    CodeGenFunction::SanitizerScope SanScope(&CGF);
1621    // Pass in void pointer and size of region as arguments to runtime
1622    // function
1623    llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1624                           llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1625
1626    llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1627
1628    llvm::FunctionType *FnType =
1629        llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1630    llvm::Value *Fn =
1631        CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1632    CGF.EmitNounwindRuntimeCall(Fn, Args);
1633  }
1634
1635   class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
1636     const CXXDestructorDecl *Dtor;
1637
1638   public:
1639     SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1640
1641     // Generate function call for handling object poisoning.
1642     // Disables tail call elimination, to prevent the current stack frame
1643     // from disappearing from the stack trace.
1644     void Emit(CodeGenFunction &CGF, Flags flags) override {
1645       const ASTRecordLayout &Layout =
1646           CGF.getContext().getASTRecordLayout(Dtor->getParent());
1647
1648       // Nothing to poison.
1649       if (Layout.getFieldCount() == 0)
1650         return;
1651
1652       // Prevent the current stack frame from disappearing from the stack trace.
1653       CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1654
1655       // Construct pointer to region to begin poisoning, and calculate poison
1656       // size, so that only members declared in this class are poisoned.
1657       ASTContext &Context = CGF.getContext();
1658       unsigned fieldIndex = 0;
1659       int startIndex = -1;
1660       // RecordDecl::field_iterator Field;
1661       for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1662         // Poison field if it is trivial
1663         if (FieldHasTrivialDestructorBody(Context, Field)) {
1664           // Start sanitizing at this field
1665           if (startIndex < 0)
1666             startIndex = fieldIndex;
1667
1668           // Currently on the last field, and it must be poisoned with the
1669           // current block.
1670           if (fieldIndex == Layout.getFieldCount() - 1) {
1671             PoisonMembers(CGF, startIndex, Layout.getFieldCount());
1672           }
1673         } else if (startIndex >= 0) {
1674           // No longer within a block of memory to poison, so poison the block
1675           PoisonMembers(CGF, startIndex, fieldIndex);
1676           // Re-set the start index
1677           startIndex = -1;
1678         }
1679         fieldIndex += 1;
1680       }
1681     }
1682
1683   private:
1684     /// \param layoutStartOffset index of the ASTRecordLayout field to
1685     ///     start poisoning (inclusive)
1686     /// \param layoutEndOffset index of the ASTRecordLayout field to
1687     ///     end poisoning (exclusive)
1688     void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
1689                      unsigned layoutEndOffset) {
1690       ASTContext &Context = CGF.getContext();
1691       const ASTRecordLayout &Layout =
1692           Context.getASTRecordLayout(Dtor->getParent());
1693
1694       llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1695           CGF.SizeTy,
1696           Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1697               .getQuantity());
1698
1699       llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1700           CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1701           OffsetSizePtr);
1702
1703       CharUnits::QuantityType PoisonSize;
1704       if (layoutEndOffset >= Layout.getFieldCount()) {
1705         PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1706                      Context.toCharUnitsFromBits(
1707                                 Layout.getFieldOffset(layoutStartOffset))
1708                          .getQuantity();
1709       } else {
1710         PoisonSize = Context.toCharUnitsFromBits(
1711                                 Layout.getFieldOffset(layoutEndOffset) -
1712                                 Layout.getFieldOffset(layoutStartOffset))
1713                          .getQuantity();
1714       }
1715
1716       if (PoisonSize == 0)
1717         return;
1718
1719       EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
1720     }
1721   };
1722
1723  class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1724     const CXXDestructorDecl *Dtor;
1725
1726   public:
1727     SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1728
1729     // Generate function call for handling vtable pointer poisoning.
1730     void Emit(CodeGenFunction &CGF, Flags flags) override {
1731       assert(Dtor->getParent()->isDynamicClass());
1732       (void)Dtor;
1733       ASTContext &Context = CGF.getContext();
1734       // Poison vtable and vtable ptr if they exist for this class.
1735       llvm::Value *VTablePtr = CGF.LoadCXXThis();
1736
1737       CharUnits::QuantityType PoisonSize =
1738           Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1739       // Pass in void pointer and size of region as arguments to runtime
1740       // function
1741       EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1742     }
1743  };
1744 } // end anonymous namespace
1745
1746 /// Emit all code that comes at the end of class's
1747 /// destructor. This is to call destructors on members and base classes
1748 /// in reverse order of their construction.
1749 ///
1750 /// For a deleting destructor, this also handles the case where a destroying
1751 /// operator delete completely overrides the definition.
1752 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1753                                         CXXDtorType DtorType) {
1754   assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1755          "Should not emit dtor epilogue for non-exported trivial dtor!");
1756
1757   // The deleting-destructor phase just needs to call the appropriate
1758   // operator delete that Sema picked up.
1759   if (DtorType == Dtor_Deleting) {
1760     assert(DD->getOperatorDelete() &&
1761            "operator delete missing - EnterDtorCleanups");
1762     if (CXXStructorImplicitParamValue) {
1763       // If there is an implicit param to the deleting dtor, it's a boolean
1764       // telling whether this is a deleting destructor.
1765       if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
1766         EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
1767                                       /*ReturnAfterDelete*/true);
1768       else
1769         EHStack.pushCleanup<CallDtorDeleteConditional>(
1770             NormalAndEHCleanup, CXXStructorImplicitParamValue);
1771     } else {
1772       if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
1773         const CXXRecordDecl *ClassDecl = DD->getParent();
1774         EmitDeleteCall(DD->getOperatorDelete(),
1775                        LoadThisForDtorDelete(*this, DD),
1776                        getContext().getTagDeclType(ClassDecl));
1777         EmitBranchThroughCleanup(ReturnBlock);
1778       } else {
1779         EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1780       }
1781     }
1782     return;
1783   }
1784
1785   const CXXRecordDecl *ClassDecl = DD->getParent();
1786
1787   // Unions have no bases and do not call field destructors.
1788   if (ClassDecl->isUnion())
1789     return;
1790
1791   // The complete-destructor phase just destructs all the virtual bases.
1792   if (DtorType == Dtor_Complete) {
1793     // Poison the vtable pointer such that access after the base
1794     // and member destructors are invoked is invalid.
1795     if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1796         SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1797         ClassDecl->isPolymorphic())
1798       EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1799
1800     // We push them in the forward order so that they'll be popped in
1801     // the reverse order.
1802     for (const auto &Base : ClassDecl->vbases()) {
1803       CXXRecordDecl *BaseClassDecl
1804         = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1805
1806       // Ignore trivial destructors.
1807       if (BaseClassDecl->hasTrivialDestructor())
1808         continue;
1809
1810       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1811                                         BaseClassDecl,
1812                                         /*BaseIsVirtual*/ true);
1813     }
1814
1815     return;
1816   }
1817
1818   assert(DtorType == Dtor_Base);
1819   // Poison the vtable pointer if it has no virtual bases, but inherits
1820   // virtual functions.
1821   if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1822       SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1823       ClassDecl->isPolymorphic())
1824     EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1825
1826   // Destroy non-virtual bases.
1827   for (const auto &Base : ClassDecl->bases()) {
1828     // Ignore virtual bases.
1829     if (Base.isVirtual())
1830       continue;
1831
1832     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1833
1834     // Ignore trivial destructors.
1835     if (BaseClassDecl->hasTrivialDestructor())
1836       continue;
1837
1838     EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1839                                       BaseClassDecl,
1840                                       /*BaseIsVirtual*/ false);
1841   }
1842
1843   // Poison fields such that access after their destructors are
1844   // invoked, and before the base class destructor runs, is invalid.
1845   if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1846       SanOpts.has(SanitizerKind::Memory))
1847     EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
1848
1849   // Destroy direct fields.
1850   for (const auto *Field : ClassDecl->fields()) {
1851     QualType type = Field->getType();
1852     QualType::DestructionKind dtorKind = type.isDestructedType();
1853     if (!dtorKind) continue;
1854
1855     // Anonymous union members do not have their destructors called.
1856     const RecordType *RT = type->getAsUnionType();
1857     if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1858
1859     CleanupKind cleanupKind = getCleanupKind(dtorKind);
1860     EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
1861                                       getDestroyer(dtorKind),
1862                                       cleanupKind & EHCleanup);
1863   }
1864 }
1865
1866 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1867 /// constructor for each of several members of an array.
1868 ///
1869 /// \param ctor the constructor to call for each element
1870 /// \param arrayType the type of the array to initialize
1871 /// \param arrayBegin an arrayType*
1872 /// \param zeroInitialize true if each element should be
1873 ///   zero-initialized before it is constructed
1874 void CodeGenFunction::EmitCXXAggrConstructorCall(
1875     const CXXConstructorDecl *ctor, const ArrayType *arrayType,
1876     Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
1877     bool zeroInitialize) {
1878   QualType elementType;
1879   llvm::Value *numElements =
1880     emitArrayLength(arrayType, elementType, arrayBegin);
1881
1882   EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
1883                              NewPointerIsChecked, zeroInitialize);
1884 }
1885
1886 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1887 /// constructor for each of several members of an array.
1888 ///
1889 /// \param ctor the constructor to call for each element
1890 /// \param numElements the number of elements in the array;
1891 ///   may be zero
1892 /// \param arrayBase a T*, where T is the type constructed by ctor
1893 /// \param zeroInitialize true if each element should be
1894 ///   zero-initialized before it is constructed
1895 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1896                                                  llvm::Value *numElements,
1897                                                  Address arrayBase,
1898                                                  const CXXConstructExpr *E,
1899                                                  bool NewPointerIsChecked,
1900                                                  bool zeroInitialize) {
1901   // It's legal for numElements to be zero.  This can happen both
1902   // dynamically, because x can be zero in 'new A[x]', and statically,
1903   // because of GCC extensions that permit zero-length arrays.  There
1904   // are probably legitimate places where we could assume that this
1905   // doesn't happen, but it's not clear that it's worth it.
1906   llvm::BranchInst *zeroCheckBranch = nullptr;
1907
1908   // Optimize for a constant count.
1909   llvm::ConstantInt *constantCount
1910     = dyn_cast<llvm::ConstantInt>(numElements);
1911   if (constantCount) {
1912     // Just skip out if the constant count is zero.
1913     if (constantCount->isZero()) return;
1914
1915   // Otherwise, emit the check.
1916   } else {
1917     llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1918     llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1919     zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1920     EmitBlock(loopBB);
1921   }
1922
1923   // Find the end of the array.
1924   llvm::Value *arrayBegin = arrayBase.getPointer();
1925   llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1926                                                     "arrayctor.end");
1927
1928   // Enter the loop, setting up a phi for the current location to initialize.
1929   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1930   llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1931   EmitBlock(loopBB);
1932   llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1933                                          "arrayctor.cur");
1934   cur->addIncoming(arrayBegin, entryBB);
1935
1936   // Inside the loop body, emit the constructor call on the array element.
1937
1938   // The alignment of the base, adjusted by the size of a single element,
1939   // provides a conservative estimate of the alignment of every element.
1940   // (This assumes we never start tracking offsetted alignments.)
1941   //
1942   // Note that these are complete objects and so we don't need to
1943   // use the non-virtual size or alignment.
1944   QualType type = getContext().getTypeDeclType(ctor->getParent());
1945   CharUnits eltAlignment =
1946     arrayBase.getAlignment()
1947              .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1948   Address curAddr = Address(cur, eltAlignment);
1949
1950   // Zero initialize the storage, if requested.
1951   if (zeroInitialize)
1952     EmitNullInitialization(curAddr, type);
1953
1954   // C++ [class.temporary]p4:
1955   // There are two contexts in which temporaries are destroyed at a different
1956   // point than the end of the full-expression. The first context is when a
1957   // default constructor is called to initialize an element of an array.
1958   // If the constructor has one or more default arguments, the destruction of
1959   // every temporary created in a default argument expression is sequenced
1960   // before the construction of the next array element, if any.
1961
1962   {
1963     RunCleanupsScope Scope(*this);
1964
1965     // Evaluate the constructor and its arguments in a regular
1966     // partial-destroy cleanup.
1967     if (getLangOpts().Exceptions &&
1968         !ctor->getParent()->hasTrivialDestructor()) {
1969       Destroyer *destroyer = destroyCXXObject;
1970       pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1971                                      *destroyer);
1972     }
1973
1974     EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1975                            /*Delegating=*/false, curAddr, E,
1976                            AggValueSlot::DoesNotOverlap, NewPointerIsChecked);
1977   }
1978
1979   // Go to the next element.
1980   llvm::Value *next =
1981     Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1982                               "arrayctor.next");
1983   cur->addIncoming(next, Builder.GetInsertBlock());
1984
1985   // Check whether that's the end of the loop.
1986   llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1987   llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1988   Builder.CreateCondBr(done, contBB, loopBB);
1989
1990   // Patch the earlier check to skip over the loop.
1991   if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1992
1993   EmitBlock(contBB);
1994 }
1995
1996 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1997                                        Address addr,
1998                                        QualType type) {
1999   const RecordType *rtype = type->castAs<RecordType>();
2000   const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
2001   const CXXDestructorDecl *dtor = record->getDestructor();
2002   assert(!dtor->isTrivial());
2003   CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
2004                             /*Delegating=*/false, addr);
2005 }
2006
2007 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2008                                              CXXCtorType Type,
2009                                              bool ForVirtualBase,
2010                                              bool Delegating, Address This,
2011                                              const CXXConstructExpr *E,
2012                                              AggValueSlot::Overlap_t Overlap,
2013                                              bool NewPointerIsChecked) {
2014   CallArgList Args;
2015
2016   LangAS SlotAS = E->getType().getAddressSpace();
2017   QualType ThisType = D->getThisType();
2018   LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
2019   llvm::Value *ThisPtr = This.getPointer();
2020   if (SlotAS != ThisAS) {
2021     unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
2022     llvm::Type *NewType =
2023         ThisPtr->getType()->getPointerElementType()->getPointerTo(TargetThisAS);
2024     ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
2025                                                     ThisAS, SlotAS, NewType);
2026   }
2027   // Push the this ptr.
2028   Args.add(RValue::get(ThisPtr), D->getThisType());
2029
2030   // If this is a trivial constructor, emit a memcpy now before we lose
2031   // the alignment information on the argument.
2032   // FIXME: It would be better to preserve alignment information into CallArg.
2033   if (isMemcpyEquivalentSpecialMember(D)) {
2034     assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2035
2036     const Expr *Arg = E->getArg(0);
2037     LValue Src = EmitLValue(Arg);
2038     QualType DestTy = getContext().getTypeDeclType(D->getParent());
2039     LValue Dest = MakeAddrLValue(This, DestTy);
2040     EmitAggregateCopyCtor(Dest, Src, Overlap);
2041     return;
2042   }
2043
2044   // Add the rest of the user-supplied arguments.
2045   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2046   EvaluationOrder Order = E->isListInitialization()
2047                               ? EvaluationOrder::ForceLeftToRight
2048                               : EvaluationOrder::Default;
2049   EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
2050                /*ParamsToSkip*/ 0, Order);
2051
2052   EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
2053                          Overlap, E->getExprLoc(), NewPointerIsChecked);
2054 }
2055
2056 static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
2057                                     const CXXConstructorDecl *Ctor,
2058                                     CXXCtorType Type, CallArgList &Args) {
2059   // We can't forward a variadic call.
2060   if (Ctor->isVariadic())
2061     return false;
2062
2063   if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2064     // If the parameters are callee-cleanup, it's not safe to forward.
2065     for (auto *P : Ctor->parameters())
2066       if (P->getType().isDestructedType())
2067         return false;
2068
2069     // Likewise if they're inalloca.
2070     const CGFunctionInfo &Info =
2071         CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
2072     if (Info.usesInAlloca())
2073       return false;
2074   }
2075
2076   // Anything else should be OK.
2077   return true;
2078 }
2079
2080 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
2081                                              CXXCtorType Type,
2082                                              bool ForVirtualBase,
2083                                              bool Delegating,
2084                                              Address This,
2085                                              CallArgList &Args,
2086                                              AggValueSlot::Overlap_t Overlap,
2087                                              SourceLocation Loc,
2088                                              bool NewPointerIsChecked) {
2089   const CXXRecordDecl *ClassDecl = D->getParent();
2090
2091   if (!NewPointerIsChecked)
2092     EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
2093                   getContext().getRecordType(ClassDecl), CharUnits::Zero());
2094
2095   if (D->isTrivial() && D->isDefaultConstructor()) {
2096     assert(Args.size() == 1 && "trivial default ctor with args");
2097     return;
2098   }
2099
2100   // If this is a trivial constructor, just emit what's needed. If this is a
2101   // union copy constructor, we must emit a memcpy, because the AST does not
2102   // model that copy.
2103   if (isMemcpyEquivalentSpecialMember(D)) {
2104     assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
2105
2106     QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2107     Address Src(Args[1].getRValue(*this).getScalarVal(),
2108                 getNaturalTypeAlignment(SrcTy));
2109     LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
2110     QualType DestTy = getContext().getTypeDeclType(ClassDecl);
2111     LValue DestLVal = MakeAddrLValue(This, DestTy);
2112     EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
2113     return;
2114   }
2115
2116   bool PassPrototypeArgs = true;
2117   // Check whether we can actually emit the constructor before trying to do so.
2118   if (auto Inherited = D->getInheritedConstructor()) {
2119     PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2120     if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
2121       EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2122                                               Delegating, Args);
2123       return;
2124     }
2125   }
2126
2127   // Insert any ABI-specific implicit constructor arguments.
2128   CGCXXABI::AddedStructorArgs ExtraArgs =
2129       CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2130                                                  Delegating, Args);
2131
2132   // Emit the call.
2133   llvm::Constant *CalleePtr =
2134     CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
2135   const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
2136       Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
2137   CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
2138   EmitCall(Info, Callee, ReturnValueSlot(), Args);
2139
2140   // Generate vtable assumptions if we're constructing a complete object
2141   // with a vtable.  We don't do this for base subobjects for two reasons:
2142   // first, it's incorrect for classes with virtual bases, and second, we're
2143   // about to overwrite the vptrs anyway.
2144   // We also have to make sure if we can refer to vtable:
2145   // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2146   // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2147   // sure that definition of vtable is not hidden,
2148   // then we are always safe to refer to it.
2149   // FIXME: It looks like InstCombine is very inefficient on dealing with
2150   // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
2151   if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2152       ClassDecl->isDynamicClass() && Type != Ctor_Base &&
2153       CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2154       CGM.getCodeGenOpts().StrictVTablePointers)
2155     EmitVTableAssumptionLoads(ClassDecl, This);
2156 }
2157
2158 void CodeGenFunction::EmitInheritedCXXConstructorCall(
2159     const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2160     bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2161   CallArgList Args;
2162   CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType());
2163
2164   // Forward the parameters.
2165   if (InheritedFromVBase &&
2166       CGM.getTarget().getCXXABI().hasConstructorVariants()) {
2167     // Nothing to do; this construction is not responsible for constructing
2168     // the base class containing the inherited constructor.
2169     // FIXME: Can we just pass undef's for the remaining arguments if we don't
2170     // have constructor variants?
2171     Args.push_back(ThisArg);
2172   } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2173     // The inheriting constructor was inlined; just inject its arguments.
2174     assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2175            "wrong number of parameters for inherited constructor call");
2176     Args = CXXInheritedCtorInitExprArgs;
2177     Args[0] = ThisArg;
2178   } else {
2179     // The inheriting constructor was not inlined. Emit delegating arguments.
2180     Args.push_back(ThisArg);
2181     const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2182     assert(OuterCtor->getNumParams() == D->getNumParams());
2183     assert(!OuterCtor->isVariadic() && "should have been inlined");
2184
2185     for (const auto *Param : OuterCtor->parameters()) {
2186       assert(getContext().hasSameUnqualifiedType(
2187           OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2188           Param->getType()));
2189       EmitDelegateCallArg(Args, Param, E->getLocation());
2190
2191       // Forward __attribute__(pass_object_size).
2192       if (Param->hasAttr<PassObjectSizeAttr>()) {
2193         auto *POSParam = SizeArguments[Param];
2194         assert(POSParam && "missing pass_object_size value for forwarding");
2195         EmitDelegateCallArg(Args, POSParam, E->getLocation());
2196       }
2197     }
2198   }
2199
2200   EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2201                          This, Args, AggValueSlot::MayOverlap,
2202                          E->getLocation(), /*NewPointerIsChecked*/true);
2203 }
2204
2205 void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
2206     const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2207     bool Delegating, CallArgList &Args) {
2208   GlobalDecl GD(Ctor, CtorType);
2209   InlinedInheritingConstructorScope Scope(*this, GD);
2210   ApplyInlineDebugLocation DebugScope(*this, GD);
2211   RunCleanupsScope RunCleanups(*this);
2212
2213   // Save the arguments to be passed to the inherited constructor.
2214   CXXInheritedCtorInitExprArgs = Args;
2215
2216   FunctionArgList Params;
2217   QualType RetType = BuildFunctionArgList(CurGD, Params);
2218   FnRetTy = RetType;
2219
2220   // Insert any ABI-specific implicit constructor arguments.
2221   CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2222                                              ForVirtualBase, Delegating, Args);
2223
2224   // Emit a simplified prolog. We only need to emit the implicit params.
2225   assert(Args.size() >= Params.size() && "too few arguments for call");
2226   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2227     if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2228       const RValue &RV = Args[I].getRValue(*this);
2229       assert(!RV.isComplex() && "complex indirect params not supported");
2230       ParamValue Val = RV.isScalar()
2231                            ? ParamValue::forDirect(RV.getScalarVal())
2232                            : ParamValue::forIndirect(RV.getAggregateAddress());
2233       EmitParmDecl(*Params[I], Val, I + 1);
2234     }
2235   }
2236
2237   // Create a return value slot if the ABI implementation wants one.
2238   // FIXME: This is dumb, we should ask the ABI not to try to set the return
2239   // value instead.
2240   if (!RetType->isVoidType())
2241     ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2242
2243   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
2244   CXXThisValue = CXXABIThisValue;
2245
2246   // Directly emit the constructor initializers.
2247   EmitCtorPrologue(Ctor, CtorType, Params);
2248 }
2249
2250 void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
2251   llvm::Value *VTableGlobal =
2252       CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
2253   if (!VTableGlobal)
2254     return;
2255
2256   // We can just use the base offset in the complete class.
2257   CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2258
2259   if (!NonVirtualOffset.isZero())
2260     This =
2261         ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2262                                         Vptr.VTableClass, Vptr.NearestVBase);
2263
2264   llvm::Value *VPtrValue =
2265       GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
2266   llvm::Value *Cmp =
2267       Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2268   Builder.CreateAssumption(Cmp);
2269 }
2270
2271 void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
2272                                                 Address This) {
2273   if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2274     for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2275       EmitVTableAssumptionLoad(Vptr, This);
2276 }
2277
2278 void
2279 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2280                                                 Address This, Address Src,
2281                                                 const CXXConstructExpr *E) {
2282   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2283
2284   CallArgList Args;
2285
2286   // Push the this ptr.
2287   Args.add(RValue::get(This.getPointer()), D->getThisType());
2288
2289   // Push the src ptr.
2290   QualType QT = *(FPT->param_type_begin());
2291   llvm::Type *t = CGM.getTypes().ConvertType(QT);
2292   Src = Builder.CreateBitCast(Src, t);
2293   Args.add(RValue::get(Src.getPointer()), QT);
2294
2295   // Skip over first argument (Src).
2296   EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
2297                /*ParamsToSkip*/ 1);
2298
2299   EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
2300                          /*Delegating*/false, This, Args,
2301                          AggValueSlot::MayOverlap, E->getExprLoc(),
2302                          /*NewPointerIsChecked*/false);
2303 }
2304
2305 void
2306 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2307                                                 CXXCtorType CtorType,
2308                                                 const FunctionArgList &Args,
2309                                                 SourceLocation Loc) {
2310   CallArgList DelegateArgs;
2311
2312   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2313   assert(I != E && "no parameters to constructor");
2314
2315   // this
2316   Address This = LoadCXXThisAddress();
2317   DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
2318   ++I;
2319
2320   // FIXME: The location of the VTT parameter in the parameter list is
2321   // specific to the Itanium ABI and shouldn't be hardcoded here.
2322   if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
2323     assert(I != E && "cannot skip vtt parameter, already done with args");
2324     assert((*I)->getType()->isPointerType() &&
2325            "skipping parameter not of vtt type");
2326     ++I;
2327   }
2328
2329   // Explicit arguments.
2330   for (; I != E; ++I) {
2331     const VarDecl *param = *I;
2332     // FIXME: per-argument source location
2333     EmitDelegateCallArg(DelegateArgs, param, Loc);
2334   }
2335
2336   EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2337                          /*Delegating=*/true, This, DelegateArgs,
2338                          AggValueSlot::MayOverlap, Loc,
2339                          /*NewPointerIsChecked=*/true);
2340 }
2341
2342 namespace {
2343   struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
2344     const CXXDestructorDecl *Dtor;
2345     Address Addr;
2346     CXXDtorType Type;
2347
2348     CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
2349                            CXXDtorType Type)
2350       : Dtor(D), Addr(Addr), Type(Type) {}
2351
2352     void Emit(CodeGenFunction &CGF, Flags flags) override {
2353       CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
2354                                 /*Delegating=*/true, Addr);
2355     }
2356   };
2357 } // end anonymous namespace
2358
2359 void
2360 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2361                                                   const FunctionArgList &Args) {
2362   assert(Ctor->isDelegatingConstructor());
2363
2364   Address ThisPtr = LoadCXXThisAddress();
2365
2366   AggValueSlot AggSlot =
2367     AggValueSlot::forAddr(ThisPtr, Qualifiers(),
2368                           AggValueSlot::IsDestructed,
2369                           AggValueSlot::DoesNotNeedGCBarriers,
2370                           AggValueSlot::IsNotAliased,
2371                           AggValueSlot::MayOverlap,
2372                           AggValueSlot::IsNotZeroed,
2373                           // Checks are made by the code that calls constructor.
2374                           AggValueSlot::IsSanitizerChecked);
2375
2376   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
2377
2378   const CXXRecordDecl *ClassDecl = Ctor->getParent();
2379   if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
2380     CXXDtorType Type =
2381       CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2382
2383     EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2384                                                 ClassDecl->getDestructor(),
2385                                                 ThisPtr, Type);
2386   }
2387 }
2388
2389 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2390                                             CXXDtorType Type,
2391                                             bool ForVirtualBase,
2392                                             bool Delegating,
2393                                             Address This) {
2394   CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2395                                      Delegating, This);
2396 }
2397
2398 namespace {
2399   struct CallLocalDtor final : EHScopeStack::Cleanup {
2400     const CXXDestructorDecl *Dtor;
2401     Address Addr;
2402
2403     CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
2404       : Dtor(D), Addr(Addr) {}
2405
2406     void Emit(CodeGenFunction &CGF, Flags flags) override {
2407       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
2408                                 /*ForVirtualBase=*/false,
2409                                 /*Delegating=*/false, Addr);
2410     }
2411   };
2412 } // end anonymous namespace
2413
2414 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
2415                                             Address Addr) {
2416   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
2417 }
2418
2419 void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
2420   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2421   if (!ClassDecl) return;
2422   if (ClassDecl->hasTrivialDestructor()) return;
2423
2424   const CXXDestructorDecl *D = ClassDecl->getDestructor();
2425   assert(D && D->isUsed() && "destructor not marked as used!");
2426   PushDestructorCleanup(D, Addr);
2427 }
2428
2429 void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
2430   // Compute the address point.
2431   llvm::Value *VTableAddressPoint =
2432       CGM.getCXXABI().getVTableAddressPointInStructor(
2433           *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2434
2435   if (!VTableAddressPoint)
2436     return;
2437
2438   // Compute where to store the address point.
2439   llvm::Value *VirtualOffset = nullptr;
2440   CharUnits NonVirtualOffset = CharUnits::Zero();
2441
2442   if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
2443     // We need to use the virtual base offset offset because the virtual base
2444     // might have a different offset in the most derived class.
2445
2446     VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2447         *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2448     NonVirtualOffset = Vptr.OffsetFromNearestVBase;
2449   } else {
2450     // We can just use the base offset in the complete class.
2451     NonVirtualOffset = Vptr.Base.getBaseOffset();
2452   }
2453
2454   // Apply the offsets.
2455   Address VTableField = LoadCXXThisAddress();
2456
2457   if (!NonVirtualOffset.isZero() || VirtualOffset)
2458     VTableField = ApplyNonVirtualAndVirtualOffset(
2459         *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2460         Vptr.NearestVBase);
2461
2462   // Finally, store the address point. Use the same LLVM types as the field to
2463   // support optimization.
2464   llvm::Type *VTablePtrTy =
2465       llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2466           ->getPointerTo()
2467           ->getPointerTo();
2468   VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2469   VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
2470
2471   llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2472   TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
2473   CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2474   if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2475       CGM.getCodeGenOpts().StrictVTablePointers)
2476     CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
2477 }
2478
2479 CodeGenFunction::VPtrsVector
2480 CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
2481   CodeGenFunction::VPtrsVector VPtrsResult;
2482   VisitedVirtualBasesSetTy VBases;
2483   getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
2484                     /*NearestVBase=*/nullptr,
2485                     /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2486                     /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2487                     VPtrsResult);
2488   return VPtrsResult;
2489 }
2490
2491 void CodeGenFunction::getVTablePointers(BaseSubobject Base,
2492                                         const CXXRecordDecl *NearestVBase,
2493                                         CharUnits OffsetFromNearestVBase,
2494                                         bool BaseIsNonVirtualPrimaryBase,
2495                                         const CXXRecordDecl *VTableClass,
2496                                         VisitedVirtualBasesSetTy &VBases,
2497                                         VPtrsVector &Vptrs) {
2498   // If this base is a non-virtual primary base the address point has already
2499   // been set.
2500   if (!BaseIsNonVirtualPrimaryBase) {
2501     // Initialize the vtable pointer for this base.
2502     VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2503     Vptrs.push_back(Vptr);
2504   }
2505
2506   const CXXRecordDecl *RD = Base.getBase();
2507
2508   // Traverse bases.
2509   for (const auto &I : RD->bases()) {
2510     CXXRecordDecl *BaseDecl
2511       = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2512
2513     // Ignore classes without a vtable.
2514     if (!BaseDecl->isDynamicClass())
2515       continue;
2516
2517     CharUnits BaseOffset;
2518     CharUnits BaseOffsetFromNearestVBase;
2519     bool BaseDeclIsNonVirtualPrimaryBase;
2520
2521     if (I.isVirtual()) {
2522       // Check if we've visited this virtual base before.
2523       if (!VBases.insert(BaseDecl).second)
2524         continue;
2525
2526       const ASTRecordLayout &Layout =
2527         getContext().getASTRecordLayout(VTableClass);
2528
2529       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2530       BaseOffsetFromNearestVBase = CharUnits::Zero();
2531       BaseDeclIsNonVirtualPrimaryBase = false;
2532     } else {
2533       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2534
2535       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2536       BaseOffsetFromNearestVBase =
2537         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2538       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2539     }
2540
2541     getVTablePointers(
2542         BaseSubobject(BaseDecl, BaseOffset),
2543         I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2544         BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
2545   }
2546 }
2547
2548 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2549   // Ignore classes without a vtable.
2550   if (!RD->isDynamicClass())
2551     return;
2552
2553   // Initialize the vtable pointers for this class and all of its bases.
2554   if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
2555     for (const VPtr &Vptr : getVTablePointers(RD))
2556       InitializeVTablePointer(Vptr);
2557
2558   if (RD->getNumVBases())
2559     CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
2560 }
2561
2562 llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
2563                                            llvm::Type *VTableTy,
2564                                            const CXXRecordDecl *RD) {
2565   Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
2566   llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2567   TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
2568   CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
2569
2570   if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2571       CGM.getCodeGenOpts().StrictVTablePointers)
2572     CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
2573
2574   return VTable;
2575 }
2576
2577 // If a class has a single non-virtual base and does not introduce or override
2578 // virtual member functions or fields, it will have the same layout as its base.
2579 // This function returns the least derived such class.
2580 //
2581 // Casting an instance of a base class to such a derived class is technically
2582 // undefined behavior, but it is a relatively common hack for introducing member
2583 // functions on class instances with specific properties (e.g. llvm::Operator)
2584 // that works under most compilers and should not have security implications, so
2585 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2586 static const CXXRecordDecl *
2587 LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2588   if (!RD->field_empty())
2589     return RD;
2590
2591   if (RD->getNumVBases() != 0)
2592     return RD;
2593
2594   if (RD->getNumBases() != 1)
2595     return RD;
2596
2597   for (const CXXMethodDecl *MD : RD->methods()) {
2598     if (MD->isVirtual()) {
2599       // Virtual member functions are only ok if they are implicit destructors
2600       // because the implicit destructor will have the same semantics as the
2601       // base class's destructor if no fields are added.
2602       if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2603         continue;
2604       return RD;
2605     }
2606   }
2607
2608   return LeastDerivedClassWithSameLayout(
2609       RD->bases_begin()->getType()->getAsCXXRecordDecl());
2610 }
2611
2612 void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
2613                                                    llvm::Value *VTable,
2614                                                    SourceLocation Loc) {
2615   if (SanOpts.has(SanitizerKind::CFIVCall))
2616     EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
2617   else if (CGM.getCodeGenOpts().WholeProgramVTables &&
2618            CGM.HasHiddenLTOVisibility(RD)) {
2619     llvm::Metadata *MD =
2620         CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2621     llvm::Value *TypeId =
2622         llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2623
2624     llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2625     llvm::Value *TypeTest =
2626         Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2627                            {CastedVTable, TypeId});
2628     Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
2629   }
2630 }
2631
2632 void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
2633                                                 llvm::Value *VTable,
2634                                                 CFITypeCheckKind TCK,
2635                                                 SourceLocation Loc) {
2636   if (!SanOpts.has(SanitizerKind::CFICastStrict))
2637     RD = LeastDerivedClassWithSameLayout(RD);
2638
2639   EmitVTablePtrCheck(RD, VTable, TCK, Loc);
2640 }
2641
2642 void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2643                                                 llvm::Value *Derived,
2644                                                 bool MayBeNull,
2645                                                 CFITypeCheckKind TCK,
2646                                                 SourceLocation Loc) {
2647   if (!getLangOpts().CPlusPlus)
2648     return;
2649
2650   auto *ClassTy = T->getAs<RecordType>();
2651   if (!ClassTy)
2652     return;
2653
2654   const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2655
2656   if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2657     return;
2658
2659   if (!SanOpts.has(SanitizerKind::CFICastStrict))
2660     ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2661
2662   llvm::BasicBlock *ContBlock = nullptr;
2663
2664   if (MayBeNull) {
2665     llvm::Value *DerivedNotNull =
2666         Builder.CreateIsNotNull(Derived, "cast.nonnull");
2667
2668     llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2669     ContBlock = createBasicBlock("cast.cont");
2670
2671     Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2672
2673     EmitBlock(CheckBlock);
2674   }
2675
2676   llvm::Value *VTable;
2677   std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
2678       *this, Address(Derived, getPointerAlign()), ClassDecl);
2679
2680   EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
2681
2682   if (MayBeNull) {
2683     Builder.CreateBr(ContBlock);
2684     EmitBlock(ContBlock);
2685   }
2686 }
2687
2688 void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
2689                                          llvm::Value *VTable,
2690                                          CFITypeCheckKind TCK,
2691                                          SourceLocation Loc) {
2692   if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2693       !CGM.HasHiddenLTOVisibility(RD))
2694     return;
2695
2696   SanitizerMask M;
2697   llvm::SanitizerStatKind SSK;
2698   switch (TCK) {
2699   case CFITCK_VCall:
2700     M = SanitizerKind::CFIVCall;
2701     SSK = llvm::SanStat_CFI_VCall;
2702     break;
2703   case CFITCK_NVCall:
2704     M = SanitizerKind::CFINVCall;
2705     SSK = llvm::SanStat_CFI_NVCall;
2706     break;
2707   case CFITCK_DerivedCast:
2708     M = SanitizerKind::CFIDerivedCast;
2709     SSK = llvm::SanStat_CFI_DerivedCast;
2710     break;
2711   case CFITCK_UnrelatedCast:
2712     M = SanitizerKind::CFIUnrelatedCast;
2713     SSK = llvm::SanStat_CFI_UnrelatedCast;
2714     break;
2715   case CFITCK_ICall:
2716   case CFITCK_NVMFCall:
2717   case CFITCK_VMFCall:
2718     llvm_unreachable("unexpected sanitizer kind");
2719   }
2720
2721   std::string TypeName = RD->getQualifiedNameAsString();
2722   if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
2723     return;
2724
2725   SanitizerScope SanScope(this);
2726   EmitSanitizerStatReport(SSK);
2727
2728   llvm::Metadata *MD =
2729       CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2730   llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
2731
2732   llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2733   llvm::Value *TypeTest = Builder.CreateCall(
2734       CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
2735
2736   llvm::Constant *StaticData[] = {
2737       llvm::ConstantInt::get(Int8Ty, TCK),
2738       EmitCheckSourceLocation(Loc),
2739       EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2740   };
2741
2742   auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2743   if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2744     EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
2745     return;
2746   }
2747
2748   if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
2749     EmitTrapCheck(TypeTest);
2750     return;
2751   }
2752
2753   llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2754       CGM.getLLVMContext(),
2755       llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2756   llvm::Value *ValidVtable = Builder.CreateCall(
2757       CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
2758   EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2759             StaticData, {CastedVTable, ValidVtable});
2760 }
2761
2762 bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
2763   if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2764       !SanOpts.has(SanitizerKind::CFIVCall) ||
2765       !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2766       !CGM.HasHiddenLTOVisibility(RD))
2767     return false;
2768
2769   std::string TypeName = RD->getQualifiedNameAsString();
2770   return !getContext().getSanitizerBlacklist().isBlacklistedType(
2771       SanitizerKind::CFIVCall, TypeName);
2772 }
2773
2774 llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
2775     const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2776   SanitizerScope SanScope(this);
2777
2778   EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2779
2780   llvm::Metadata *MD =
2781       CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
2782   llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2783
2784   llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2785   llvm::Value *CheckedLoad = Builder.CreateCall(
2786       CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2787       {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2788        TypeId});
2789   llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2790
2791   EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
2792             SanitizerHandler::CFICheckFail, nullptr, nullptr);
2793
2794   return Builder.CreateBitCast(
2795       Builder.CreateExtractValue(CheckedLoad, 0),
2796       cast<llvm::PointerType>(VTable->getType())->getElementType());
2797 }
2798
2799 void CodeGenFunction::EmitForwardingCallToLambda(
2800                                       const CXXMethodDecl *callOperator,
2801                                       CallArgList &callArgs) {
2802   // Get the address of the call operator.
2803   const CGFunctionInfo &calleeFnInfo =
2804     CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2805   llvm::Constant *calleePtr =
2806     CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2807                           CGM.getTypes().GetFunctionType(calleeFnInfo));
2808
2809   // Prepare the return slot.
2810   const FunctionProtoType *FPT =
2811     callOperator->getType()->castAs<FunctionProtoType>();
2812   QualType resultType = FPT->getReturnType();
2813   ReturnValueSlot returnSlot;
2814   if (!resultType->isVoidType() &&
2815       calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2816       !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2817     returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2818
2819   // We don't need to separately arrange the call arguments because
2820   // the call can't be variadic anyway --- it's impossible to forward
2821   // variadic arguments.
2822
2823   // Now emit our call.
2824   auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
2825   RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
2826
2827   // If necessary, copy the returned value into the slot.
2828   if (!resultType->isVoidType() && returnSlot.isNull()) {
2829     if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
2830       RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
2831     }
2832     EmitReturnOfRValue(RV, resultType);
2833   } else
2834     EmitBranchThroughCleanup(ReturnBlock);
2835 }
2836
2837 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2838   const BlockDecl *BD = BlockInfo->getBlockDecl();
2839   const VarDecl *variable = BD->capture_begin()->getVariable();
2840   const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2841   const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2842
2843   if (CallOp->isVariadic()) {
2844     // FIXME: Making this work correctly is nasty because it requires either
2845     // cloning the body of the call operator or making the call operator
2846     // forward.
2847     CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2848     return;
2849   }
2850
2851   // Start building arguments for forwarding call
2852   CallArgList CallArgs;
2853
2854   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2855   Address ThisPtr = GetAddrOfBlockDecl(variable);
2856   CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
2857
2858   // Add the rest of the parameters.
2859   for (auto param : BD->parameters())
2860     EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
2861
2862   assert(!Lambda->isGenericLambda() &&
2863             "generic lambda interconversion to block not implemented");
2864   EmitForwardingCallToLambda(CallOp, CallArgs);
2865 }
2866
2867 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2868   const CXXRecordDecl *Lambda = MD->getParent();
2869
2870   // Start building arguments for forwarding call
2871   CallArgList CallArgs;
2872
2873   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2874   llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2875   CallArgs.add(RValue::get(ThisPtr), ThisType);
2876
2877   // Add the rest of the parameters.
2878   for (auto Param : MD->parameters())
2879     EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
2880
2881   const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2882   // For a generic lambda, find the corresponding call operator specialization
2883   // to which the call to the static-invoker shall be forwarded.
2884   if (Lambda->isGenericLambda()) {
2885     assert(MD->isFunctionTemplateSpecialization());
2886     const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2887     FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2888     void *InsertPos = nullptr;
2889     FunctionDecl *CorrespondingCallOpSpecialization =
2890         CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
2891     assert(CorrespondingCallOpSpecialization);
2892     CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2893   }
2894   EmitForwardingCallToLambda(CallOp, CallArgs);
2895 }
2896
2897 void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
2898   if (MD->isVariadic()) {
2899     // FIXME: Making this work correctly is nasty because it requires either
2900     // cloning the body of the call operator or making the call operator forward.
2901     CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2902     return;
2903   }
2904
2905   EmitLambdaDelegatingInvokeBody(MD);
2906 }