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