CGClass.cpp 112 KB

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