CGClass.cpp 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893
  1. //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code dealing with C++ code generation of classes
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGBlocks.h"
  14. #include "CGCXXABI.h"
  15. #include "CGDebugInfo.h"
  16. #include "CGRecordLayout.h"
  17. #include "CodeGenFunction.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/TargetBuiltins.h"
  24. #include "clang/CodeGen/CGFunctionInfo.h"
  25. #include "clang/Frontend/CodeGenOptions.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())->getPointerTo();
  261. QualType DerivedTy = getContext().getRecordType(Derived);
  262. CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
  263. // If the static offset is zero and we don't have a virtual step,
  264. // just do a bitcast; null checks are unnecessary.
  265. if (NonVirtualOffset.isZero() && !VBase) {
  266. if (sanitizePerformTypeCheck()) {
  267. SanitizerSet SkippedChecks;
  268. SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
  269. EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
  270. DerivedTy, DerivedAlign, SkippedChecks);
  271. }
  272. return Builder.CreateBitCast(Value, BasePtrTy);
  273. }
  274. llvm::BasicBlock *origBB = nullptr;
  275. llvm::BasicBlock *endBB = nullptr;
  276. // Skip over the offset (and the vtable load) if we're supposed to
  277. // null-check the pointer.
  278. if (NullCheckValue) {
  279. origBB = Builder.GetInsertBlock();
  280. llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
  281. endBB = createBasicBlock("cast.end");
  282. llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
  283. Builder.CreateCondBr(isNull, endBB, notNullBB);
  284. EmitBlock(notNullBB);
  285. }
  286. if (sanitizePerformTypeCheck()) {
  287. SanitizerSet SkippedChecks;
  288. SkippedChecks.set(SanitizerKind::Null, true);
  289. EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
  290. Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
  291. }
  292. // Compute the virtual offset.
  293. llvm::Value *VirtualOffset = nullptr;
  294. if (VBase) {
  295. VirtualOffset =
  296. CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
  297. }
  298. // Apply both offsets.
  299. Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
  300. VirtualOffset, Derived, VBase);
  301. // Cast to the destination type.
  302. Value = Builder.CreateBitCast(Value, BasePtrTy);
  303. // Build a phi if we needed a null check.
  304. if (NullCheckValue) {
  305. llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
  306. Builder.CreateBr(endBB);
  307. EmitBlock(endBB);
  308. llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
  309. PHI->addIncoming(Value.getPointer(), notNullBB);
  310. PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
  311. Value = Address(PHI, Value.getAlignment());
  312. }
  313. return Value;
  314. }
  315. Address
  316. CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
  317. const CXXRecordDecl *Derived,
  318. CastExpr::path_const_iterator PathBegin,
  319. CastExpr::path_const_iterator PathEnd,
  320. bool NullCheckValue) {
  321. assert(PathBegin != PathEnd && "Base path should not be empty!");
  322. QualType DerivedTy =
  323. getContext().getCanonicalType(getContext().getTagDeclType(Derived));
  324. llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
  325. llvm::Value *NonVirtualOffset =
  326. CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
  327. if (!NonVirtualOffset) {
  328. // No offset, we can just cast back.
  329. return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
  330. }
  331. llvm::BasicBlock *CastNull = nullptr;
  332. llvm::BasicBlock *CastNotNull = nullptr;
  333. llvm::BasicBlock *CastEnd = nullptr;
  334. if (NullCheckValue) {
  335. CastNull = createBasicBlock("cast.null");
  336. CastNotNull = createBasicBlock("cast.notnull");
  337. CastEnd = createBasicBlock("cast.end");
  338. llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
  339. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  340. EmitBlock(CastNotNull);
  341. }
  342. // Apply the offset.
  343. llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
  344. Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
  345. "sub.ptr");
  346. // Just cast.
  347. Value = Builder.CreateBitCast(Value, DerivedPtrTy);
  348. // Produce a PHI if we had a null-check.
  349. if (NullCheckValue) {
  350. Builder.CreateBr(CastEnd);
  351. EmitBlock(CastNull);
  352. Builder.CreateBr(CastEnd);
  353. EmitBlock(CastEnd);
  354. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  355. PHI->addIncoming(Value, CastNotNull);
  356. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
  357. Value = PHI;
  358. }
  359. return Address(Value, CGM.getClassPointerAlignment(Derived));
  360. }
  361. llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
  362. bool ForVirtualBase,
  363. bool Delegating) {
  364. if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
  365. // This constructor/destructor does not need a VTT parameter.
  366. return nullptr;
  367. }
  368. const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
  369. const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  370. llvm::Value *VTT;
  371. uint64_t SubVTTIndex;
  372. if (Delegating) {
  373. // If this is a delegating constructor call, just load the VTT.
  374. return LoadCXXVTT();
  375. } else if (RD == Base) {
  376. // If the record matches the base, this is the complete ctor/dtor
  377. // variant calling the base variant in a class with virtual bases.
  378. assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
  379. "doing no-op VTT offset in base dtor/ctor?");
  380. assert(!ForVirtualBase && "Can't have same class as virtual base!");
  381. SubVTTIndex = 0;
  382. } else {
  383. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  384. CharUnits BaseOffset = ForVirtualBase ?
  385. Layout.getVBaseClassOffset(Base) :
  386. Layout.getBaseClassOffset(Base);
  387. SubVTTIndex =
  388. CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
  389. assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
  390. }
  391. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  392. // A VTT parameter was passed to the constructor, use it.
  393. VTT = LoadCXXVTT();
  394. VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
  395. } else {
  396. // We're the complete constructor, so get the VTT by name.
  397. VTT = CGM.getVTables().GetAddrOfVTT(RD);
  398. VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
  399. }
  400. return VTT;
  401. }
  402. namespace {
  403. /// Call the destructor for a direct base class.
  404. struct CallBaseDtor final : EHScopeStack::Cleanup {
  405. const CXXRecordDecl *BaseClass;
  406. bool BaseIsVirtual;
  407. CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
  408. : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
  409. void Emit(CodeGenFunction &CGF, Flags flags) override {
  410. const CXXRecordDecl *DerivedClass =
  411. cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
  412. const CXXDestructorDecl *D = BaseClass->getDestructor();
  413. Address Addr =
  414. CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
  415. DerivedClass, BaseClass,
  416. BaseIsVirtual);
  417. CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
  418. /*Delegating=*/false, Addr);
  419. }
  420. };
  421. /// A visitor which checks whether an initializer uses 'this' in a
  422. /// way which requires the vtable to be properly set.
  423. struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
  424. typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
  425. bool UsesThis;
  426. DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
  427. // Black-list all explicit and implicit references to 'this'.
  428. //
  429. // Do we need to worry about external references to 'this' derived
  430. // from arbitrary code? If so, then anything which runs arbitrary
  431. // external code might potentially access the vtable.
  432. void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
  433. };
  434. } // end anonymous namespace
  435. static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
  436. DynamicThisUseChecker Checker(C);
  437. Checker.Visit(Init);
  438. return Checker.UsesThis;
  439. }
  440. static void EmitBaseInitializer(CodeGenFunction &CGF,
  441. const CXXRecordDecl *ClassDecl,
  442. CXXCtorInitializer *BaseInit,
  443. CXXCtorType CtorType) {
  444. assert(BaseInit->isBaseInitializer() &&
  445. "Must have base initializer!");
  446. Address ThisPtr = CGF.LoadCXXThisAddress();
  447. const Type *BaseType = BaseInit->getBaseClass();
  448. CXXRecordDecl *BaseClassDecl =
  449. cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
  450. bool isBaseVirtual = BaseInit->isBaseVirtual();
  451. // The base constructor doesn't construct virtual bases.
  452. if (CtorType == Ctor_Base && isBaseVirtual)
  453. return;
  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.overlapForBaseInit(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.overlapForFieldInit(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. overlapForFieldInit(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::Constant *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. llvm::BasicBlock *BaseCtorContinueBB = nullptr;
  1088. if (ClassDecl->getNumVBases() &&
  1089. !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  1090. // The ABIs that don't have constructor variants need to put a branch
  1091. // before the virtual base initialization code.
  1092. BaseCtorContinueBB =
  1093. CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
  1094. assert(BaseCtorContinueBB);
  1095. }
  1096. llvm::Value *const OldThis = CXXThisValue;
  1097. // Virtual base initializers first.
  1098. for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
  1099. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1100. CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1101. isInitializerOfDynamicClass(*B))
  1102. CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
  1103. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  1104. }
  1105. if (BaseCtorContinueBB) {
  1106. // Complete object handler should continue to the remaining initializers.
  1107. Builder.CreateBr(BaseCtorContinueBB);
  1108. EmitBlock(BaseCtorContinueBB);
  1109. }
  1110. // Then, non-virtual base initializers.
  1111. for (; B != E && (*B)->isBaseInitializer(); B++) {
  1112. assert(!(*B)->isBaseVirtual());
  1113. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1114. CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1115. isInitializerOfDynamicClass(*B))
  1116. CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
  1117. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  1118. }
  1119. CXXThisValue = OldThis;
  1120. InitializeVTablePointers(ClassDecl);
  1121. // And finally, initialize class members.
  1122. FieldConstructionScope FCS(*this, LoadCXXThisAddress());
  1123. ConstructorMemcpyizer CM(*this, CD, Args);
  1124. for (; B != E; B++) {
  1125. CXXCtorInitializer *Member = (*B);
  1126. assert(!Member->isBaseInitializer());
  1127. assert(Member->isAnyMemberInitializer() &&
  1128. "Delegating initializer on non-delegating constructor");
  1129. CM.addMemberInitializer(Member);
  1130. }
  1131. CM.finish();
  1132. }
  1133. static bool
  1134. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  1135. static bool
  1136. HasTrivialDestructorBody(ASTContext &Context,
  1137. const CXXRecordDecl *BaseClassDecl,
  1138. const CXXRecordDecl *MostDerivedClassDecl)
  1139. {
  1140. // If the destructor is trivial we don't have to check anything else.
  1141. if (BaseClassDecl->hasTrivialDestructor())
  1142. return true;
  1143. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  1144. return false;
  1145. // Check fields.
  1146. for (const auto *Field : BaseClassDecl->fields())
  1147. if (!FieldHasTrivialDestructorBody(Context, Field))
  1148. return false;
  1149. // Check non-virtual bases.
  1150. for (const auto &I : BaseClassDecl->bases()) {
  1151. if (I.isVirtual())
  1152. continue;
  1153. const CXXRecordDecl *NonVirtualBase =
  1154. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1155. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  1156. MostDerivedClassDecl))
  1157. return false;
  1158. }
  1159. if (BaseClassDecl == MostDerivedClassDecl) {
  1160. // Check virtual bases.
  1161. for (const auto &I : BaseClassDecl->vbases()) {
  1162. const CXXRecordDecl *VirtualBase =
  1163. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1164. if (!HasTrivialDestructorBody(Context, VirtualBase,
  1165. MostDerivedClassDecl))
  1166. return false;
  1167. }
  1168. }
  1169. return true;
  1170. }
  1171. static bool
  1172. FieldHasTrivialDestructorBody(ASTContext &Context,
  1173. const FieldDecl *Field)
  1174. {
  1175. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  1176. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  1177. if (!RT)
  1178. return true;
  1179. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  1180. // The destructor for an implicit anonymous union member is never invoked.
  1181. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  1182. return false;
  1183. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  1184. }
  1185. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  1186. /// any vtable pointers before calling this destructor.
  1187. static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
  1188. const CXXDestructorDecl *Dtor) {
  1189. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1190. if (!ClassDecl->isDynamicClass())
  1191. return true;
  1192. if (!Dtor->hasTrivialBody())
  1193. return false;
  1194. // Check the fields.
  1195. for (const auto *Field : ClassDecl->fields())
  1196. if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
  1197. return false;
  1198. return true;
  1199. }
  1200. /// EmitDestructorBody - Emits the body of the current destructor.
  1201. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  1202. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  1203. CXXDtorType DtorType = CurGD.getDtorType();
  1204. // For an abstract class, non-base destructors are never used (and can't
  1205. // be emitted in general, because vbase dtors may not have been validated
  1206. // by Sema), but the Itanium ABI doesn't make them optional and Clang may
  1207. // in fact emit references to them from other compilations, so emit them
  1208. // as functions containing a trap instruction.
  1209. if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
  1210. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  1211. TrapCall->setDoesNotReturn();
  1212. TrapCall->setDoesNotThrow();
  1213. Builder.CreateUnreachable();
  1214. Builder.ClearInsertionPoint();
  1215. return;
  1216. }
  1217. Stmt *Body = Dtor->getBody();
  1218. if (Body)
  1219. incrementProfileCounter(Body);
  1220. // The call to operator delete in a deleting destructor happens
  1221. // outside of the function-try-block, which means it's always
  1222. // possible to delegate the destructor body to the complete
  1223. // destructor. Do so.
  1224. if (DtorType == Dtor_Deleting) {
  1225. RunCleanupsScope DtorEpilogue(*this);
  1226. EnterDtorCleanups(Dtor, Dtor_Deleting);
  1227. if (HaveInsertPoint())
  1228. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  1229. /*Delegating=*/false, LoadCXXThisAddress());
  1230. return;
  1231. }
  1232. // If the body is a function-try-block, enter the try before
  1233. // anything else.
  1234. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  1235. if (isTryBody)
  1236. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1237. EmitAsanPrologueOrEpilogue(false);
  1238. // Enter the epilogue cleanups.
  1239. RunCleanupsScope DtorEpilogue(*this);
  1240. // If this is the complete variant, just invoke the base variant;
  1241. // the epilogue will destruct the virtual bases. But we can't do
  1242. // this optimization if the body is a function-try-block, because
  1243. // we'd introduce *two* handler blocks. In the Microsoft ABI, we
  1244. // always delegate because we might not have a definition in this TU.
  1245. switch (DtorType) {
  1246. case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
  1247. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  1248. case Dtor_Complete:
  1249. assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
  1250. "can't emit a dtor without a body for non-Microsoft ABIs");
  1251. // Enter the cleanup scopes for virtual bases.
  1252. EnterDtorCleanups(Dtor, Dtor_Complete);
  1253. if (!isTryBody) {
  1254. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  1255. /*Delegating=*/false, LoadCXXThisAddress());
  1256. break;
  1257. }
  1258. // Fallthrough: act like we're in the base variant.
  1259. LLVM_FALLTHROUGH;
  1260. case Dtor_Base:
  1261. assert(Body);
  1262. // Enter the cleanup scopes for fields and non-virtual bases.
  1263. EnterDtorCleanups(Dtor, Dtor_Base);
  1264. // Initialize the vtable pointers before entering the body.
  1265. if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
  1266. // Insert the llvm.launder.invariant.group intrinsic before initializing
  1267. // the vptrs to cancel any previous assumptions we might have made.
  1268. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1269. CGM.getCodeGenOpts().OptimizationLevel > 0)
  1270. CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
  1271. InitializeVTablePointers(Dtor->getParent());
  1272. }
  1273. if (isTryBody)
  1274. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  1275. else if (Body)
  1276. EmitStmt(Body);
  1277. else {
  1278. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  1279. // nothing to do besides what's in the epilogue
  1280. }
  1281. // -fapple-kext must inline any call to this dtor into
  1282. // the caller's body.
  1283. if (getLangOpts().AppleKext)
  1284. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  1285. break;
  1286. }
  1287. // Jump out through the epilogue cleanups.
  1288. DtorEpilogue.ForceCleanup();
  1289. // Exit the try if applicable.
  1290. if (isTryBody)
  1291. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1292. }
  1293. void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
  1294. const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
  1295. const Stmt *RootS = AssignOp->getBody();
  1296. assert(isa<CompoundStmt>(RootS) &&
  1297. "Body of an implicit assignment operator should be compound stmt.");
  1298. const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
  1299. LexicalScope Scope(*this, RootCS->getSourceRange());
  1300. incrementProfileCounter(RootCS);
  1301. AssignmentMemcpyizer AM(*this, AssignOp, Args);
  1302. for (auto *I : RootCS->body())
  1303. AM.emitAssignment(I);
  1304. AM.finish();
  1305. }
  1306. namespace {
  1307. llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
  1308. const CXXDestructorDecl *DD) {
  1309. if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
  1310. return CGF.EmitScalarExpr(ThisArg);
  1311. return CGF.LoadCXXThis();
  1312. }
  1313. /// Call the operator delete associated with the current destructor.
  1314. struct CallDtorDelete final : EHScopeStack::Cleanup {
  1315. CallDtorDelete() {}
  1316. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1317. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1318. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1319. CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
  1320. LoadThisForDtorDelete(CGF, Dtor),
  1321. CGF.getContext().getTagDeclType(ClassDecl));
  1322. }
  1323. };
  1324. void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
  1325. llvm::Value *ShouldDeleteCondition,
  1326. bool ReturnAfterDelete) {
  1327. llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
  1328. llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
  1329. llvm::Value *ShouldCallDelete
  1330. = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
  1331. CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
  1332. CGF.EmitBlock(callDeleteBB);
  1333. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1334. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1335. CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
  1336. LoadThisForDtorDelete(CGF, Dtor),
  1337. CGF.getContext().getTagDeclType(ClassDecl));
  1338. assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
  1339. ReturnAfterDelete &&
  1340. "unexpected value for ReturnAfterDelete");
  1341. if (ReturnAfterDelete)
  1342. CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
  1343. else
  1344. CGF.Builder.CreateBr(continueBB);
  1345. CGF.EmitBlock(continueBB);
  1346. }
  1347. struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
  1348. llvm::Value *ShouldDeleteCondition;
  1349. public:
  1350. CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
  1351. : ShouldDeleteCondition(ShouldDeleteCondition) {
  1352. assert(ShouldDeleteCondition != nullptr);
  1353. }
  1354. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1355. EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
  1356. /*ReturnAfterDelete*/false);
  1357. }
  1358. };
  1359. class DestroyField final : public EHScopeStack::Cleanup {
  1360. const FieldDecl *field;
  1361. CodeGenFunction::Destroyer *destroyer;
  1362. bool useEHCleanupForArray;
  1363. public:
  1364. DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
  1365. bool useEHCleanupForArray)
  1366. : field(field), destroyer(destroyer),
  1367. useEHCleanupForArray(useEHCleanupForArray) {}
  1368. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1369. // Find the address of the field.
  1370. Address thisValue = CGF.LoadCXXThisAddress();
  1371. QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
  1372. LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
  1373. LValue LV = CGF.EmitLValueForField(ThisLV, field);
  1374. assert(LV.isSimple());
  1375. CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
  1376. flags.isForNormalCleanup() && useEHCleanupForArray);
  1377. }
  1378. };
  1379. static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
  1380. CharUnits::QuantityType PoisonSize) {
  1381. CodeGenFunction::SanitizerScope SanScope(&CGF);
  1382. // Pass in void pointer and size of region as arguments to runtime
  1383. // function
  1384. llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
  1385. llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
  1386. llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
  1387. llvm::FunctionType *FnType =
  1388. llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
  1389. llvm::Value *Fn =
  1390. CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
  1391. CGF.EmitNounwindRuntimeCall(Fn, Args);
  1392. }
  1393. class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
  1394. const CXXDestructorDecl *Dtor;
  1395. public:
  1396. SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
  1397. // Generate function call for handling object poisoning.
  1398. // Disables tail call elimination, to prevent the current stack frame
  1399. // from disappearing from the stack trace.
  1400. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1401. const ASTRecordLayout &Layout =
  1402. CGF.getContext().getASTRecordLayout(Dtor->getParent());
  1403. // Nothing to poison.
  1404. if (Layout.getFieldCount() == 0)
  1405. return;
  1406. // Prevent the current stack frame from disappearing from the stack trace.
  1407. CGF.CurFn->addFnAttr("disable-tail-calls", "true");
  1408. // Construct pointer to region to begin poisoning, and calculate poison
  1409. // size, so that only members declared in this class are poisoned.
  1410. ASTContext &Context = CGF.getContext();
  1411. unsigned fieldIndex = 0;
  1412. int startIndex = -1;
  1413. // RecordDecl::field_iterator Field;
  1414. for (const FieldDecl *Field : Dtor->getParent()->fields()) {
  1415. // Poison field if it is trivial
  1416. if (FieldHasTrivialDestructorBody(Context, Field)) {
  1417. // Start sanitizing at this field
  1418. if (startIndex < 0)
  1419. startIndex = fieldIndex;
  1420. // Currently on the last field, and it must be poisoned with the
  1421. // current block.
  1422. if (fieldIndex == Layout.getFieldCount() - 1) {
  1423. PoisonMembers(CGF, startIndex, Layout.getFieldCount());
  1424. }
  1425. } else if (startIndex >= 0) {
  1426. // No longer within a block of memory to poison, so poison the block
  1427. PoisonMembers(CGF, startIndex, fieldIndex);
  1428. // Re-set the start index
  1429. startIndex = -1;
  1430. }
  1431. fieldIndex += 1;
  1432. }
  1433. }
  1434. private:
  1435. /// \param layoutStartOffset index of the ASTRecordLayout field to
  1436. /// start poisoning (inclusive)
  1437. /// \param layoutEndOffset index of the ASTRecordLayout field to
  1438. /// end poisoning (exclusive)
  1439. void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
  1440. unsigned layoutEndOffset) {
  1441. ASTContext &Context = CGF.getContext();
  1442. const ASTRecordLayout &Layout =
  1443. Context.getASTRecordLayout(Dtor->getParent());
  1444. llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
  1445. CGF.SizeTy,
  1446. Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
  1447. .getQuantity());
  1448. llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
  1449. CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
  1450. OffsetSizePtr);
  1451. CharUnits::QuantityType PoisonSize;
  1452. if (layoutEndOffset >= Layout.getFieldCount()) {
  1453. PoisonSize = Layout.getNonVirtualSize().getQuantity() -
  1454. Context.toCharUnitsFromBits(
  1455. Layout.getFieldOffset(layoutStartOffset))
  1456. .getQuantity();
  1457. } else {
  1458. PoisonSize = Context.toCharUnitsFromBits(
  1459. Layout.getFieldOffset(layoutEndOffset) -
  1460. Layout.getFieldOffset(layoutStartOffset))
  1461. .getQuantity();
  1462. }
  1463. if (PoisonSize == 0)
  1464. return;
  1465. EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
  1466. }
  1467. };
  1468. class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
  1469. const CXXDestructorDecl *Dtor;
  1470. public:
  1471. SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
  1472. // Generate function call for handling vtable pointer poisoning.
  1473. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1474. assert(Dtor->getParent()->isDynamicClass());
  1475. (void)Dtor;
  1476. ASTContext &Context = CGF.getContext();
  1477. // Poison vtable and vtable ptr if they exist for this class.
  1478. llvm::Value *VTablePtr = CGF.LoadCXXThis();
  1479. CharUnits::QuantityType PoisonSize =
  1480. Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
  1481. // Pass in void pointer and size of region as arguments to runtime
  1482. // function
  1483. EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
  1484. }
  1485. };
  1486. } // end anonymous namespace
  1487. /// Emit all code that comes at the end of class's
  1488. /// destructor. This is to call destructors on members and base classes
  1489. /// in reverse order of their construction.
  1490. ///
  1491. /// For a deleting destructor, this also handles the case where a destroying
  1492. /// operator delete completely overrides the definition.
  1493. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  1494. CXXDtorType DtorType) {
  1495. assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
  1496. "Should not emit dtor epilogue for non-exported trivial dtor!");
  1497. // The deleting-destructor phase just needs to call the appropriate
  1498. // operator delete that Sema picked up.
  1499. if (DtorType == Dtor_Deleting) {
  1500. assert(DD->getOperatorDelete() &&
  1501. "operator delete missing - EnterDtorCleanups");
  1502. if (CXXStructorImplicitParamValue) {
  1503. // If there is an implicit param to the deleting dtor, it's a boolean
  1504. // telling whether this is a deleting destructor.
  1505. if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
  1506. EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
  1507. /*ReturnAfterDelete*/true);
  1508. else
  1509. EHStack.pushCleanup<CallDtorDeleteConditional>(
  1510. NormalAndEHCleanup, CXXStructorImplicitParamValue);
  1511. } else {
  1512. if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
  1513. const CXXRecordDecl *ClassDecl = DD->getParent();
  1514. EmitDeleteCall(DD->getOperatorDelete(),
  1515. LoadThisForDtorDelete(*this, DD),
  1516. getContext().getTagDeclType(ClassDecl));
  1517. EmitBranchThroughCleanup(ReturnBlock);
  1518. } else {
  1519. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  1520. }
  1521. }
  1522. return;
  1523. }
  1524. const CXXRecordDecl *ClassDecl = DD->getParent();
  1525. // Unions have no bases and do not call field destructors.
  1526. if (ClassDecl->isUnion())
  1527. return;
  1528. // The complete-destructor phase just destructs all the virtual bases.
  1529. if (DtorType == Dtor_Complete) {
  1530. // Poison the vtable pointer such that access after the base
  1531. // and member destructors are invoked is invalid.
  1532. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1533. SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
  1534. ClassDecl->isPolymorphic())
  1535. EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
  1536. // We push them in the forward order so that they'll be popped in
  1537. // the reverse order.
  1538. for (const auto &Base : ClassDecl->vbases()) {
  1539. CXXRecordDecl *BaseClassDecl
  1540. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  1541. // Ignore trivial destructors.
  1542. if (BaseClassDecl->hasTrivialDestructor())
  1543. continue;
  1544. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1545. BaseClassDecl,
  1546. /*BaseIsVirtual*/ true);
  1547. }
  1548. return;
  1549. }
  1550. assert(DtorType == Dtor_Base);
  1551. // Poison the vtable pointer if it has no virtual bases, but inherits
  1552. // virtual functions.
  1553. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1554. SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
  1555. ClassDecl->isPolymorphic())
  1556. EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
  1557. // Destroy non-virtual bases.
  1558. for (const auto &Base : ClassDecl->bases()) {
  1559. // Ignore virtual bases.
  1560. if (Base.isVirtual())
  1561. continue;
  1562. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  1563. // Ignore trivial destructors.
  1564. if (BaseClassDecl->hasTrivialDestructor())
  1565. continue;
  1566. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1567. BaseClassDecl,
  1568. /*BaseIsVirtual*/ false);
  1569. }
  1570. // Poison fields such that access after their destructors are
  1571. // invoked, and before the base class destructor runs, is invalid.
  1572. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1573. SanOpts.has(SanitizerKind::Memory))
  1574. EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
  1575. // Destroy direct fields.
  1576. for (const auto *Field : ClassDecl->fields()) {
  1577. QualType type = Field->getType();
  1578. QualType::DestructionKind dtorKind = type.isDestructedType();
  1579. if (!dtorKind) continue;
  1580. // Anonymous union members do not have their destructors called.
  1581. const RecordType *RT = type->getAsUnionType();
  1582. if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
  1583. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1584. EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
  1585. getDestroyer(dtorKind),
  1586. cleanupKind & EHCleanup);
  1587. }
  1588. }
  1589. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1590. /// constructor for each of several members of an array.
  1591. ///
  1592. /// \param ctor the constructor to call for each element
  1593. /// \param arrayType the type of the array to initialize
  1594. /// \param arrayBegin an arrayType*
  1595. /// \param zeroInitialize true if each element should be
  1596. /// zero-initialized before it is constructed
  1597. void CodeGenFunction::EmitCXXAggrConstructorCall(
  1598. const CXXConstructorDecl *ctor, const ArrayType *arrayType,
  1599. Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
  1600. bool zeroInitialize) {
  1601. QualType elementType;
  1602. llvm::Value *numElements =
  1603. emitArrayLength(arrayType, elementType, arrayBegin);
  1604. EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
  1605. NewPointerIsChecked, zeroInitialize);
  1606. }
  1607. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1608. /// constructor for each of several members of an array.
  1609. ///
  1610. /// \param ctor the constructor to call for each element
  1611. /// \param numElements the number of elements in the array;
  1612. /// may be zero
  1613. /// \param arrayBase a T*, where T is the type constructed by ctor
  1614. /// \param zeroInitialize true if each element should be
  1615. /// zero-initialized before it is constructed
  1616. void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  1617. llvm::Value *numElements,
  1618. Address arrayBase,
  1619. const CXXConstructExpr *E,
  1620. bool NewPointerIsChecked,
  1621. bool zeroInitialize) {
  1622. // It's legal for numElements to be zero. This can happen both
  1623. // dynamically, because x can be zero in 'new A[x]', and statically,
  1624. // because of GCC extensions that permit zero-length arrays. There
  1625. // are probably legitimate places where we could assume that this
  1626. // doesn't happen, but it's not clear that it's worth it.
  1627. llvm::BranchInst *zeroCheckBranch = nullptr;
  1628. // Optimize for a constant count.
  1629. llvm::ConstantInt *constantCount
  1630. = dyn_cast<llvm::ConstantInt>(numElements);
  1631. if (constantCount) {
  1632. // Just skip out if the constant count is zero.
  1633. if (constantCount->isZero()) return;
  1634. // Otherwise, emit the check.
  1635. } else {
  1636. llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
  1637. llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
  1638. zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
  1639. EmitBlock(loopBB);
  1640. }
  1641. // Find the end of the array.
  1642. llvm::Value *arrayBegin = arrayBase.getPointer();
  1643. llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
  1644. "arrayctor.end");
  1645. // Enter the loop, setting up a phi for the current location to initialize.
  1646. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1647. llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
  1648. EmitBlock(loopBB);
  1649. llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
  1650. "arrayctor.cur");
  1651. cur->addIncoming(arrayBegin, entryBB);
  1652. // Inside the loop body, emit the constructor call on the array element.
  1653. // The alignment of the base, adjusted by the size of a single element,
  1654. // provides a conservative estimate of the alignment of every element.
  1655. // (This assumes we never start tracking offsetted alignments.)
  1656. //
  1657. // Note that these are complete objects and so we don't need to
  1658. // use the non-virtual size or alignment.
  1659. QualType type = getContext().getTypeDeclType(ctor->getParent());
  1660. CharUnits eltAlignment =
  1661. arrayBase.getAlignment()
  1662. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1663. Address curAddr = Address(cur, eltAlignment);
  1664. // Zero initialize the storage, if requested.
  1665. if (zeroInitialize)
  1666. EmitNullInitialization(curAddr, type);
  1667. // C++ [class.temporary]p4:
  1668. // There are two contexts in which temporaries are destroyed at a different
  1669. // point than the end of the full-expression. The first context is when a
  1670. // default constructor is called to initialize an element of an array.
  1671. // If the constructor has one or more default arguments, the destruction of
  1672. // every temporary created in a default argument expression is sequenced
  1673. // before the construction of the next array element, if any.
  1674. {
  1675. RunCleanupsScope Scope(*this);
  1676. // Evaluate the constructor and its arguments in a regular
  1677. // partial-destroy cleanup.
  1678. if (getLangOpts().Exceptions &&
  1679. !ctor->getParent()->hasTrivialDestructor()) {
  1680. Destroyer *destroyer = destroyCXXObject;
  1681. pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
  1682. *destroyer);
  1683. }
  1684. EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
  1685. /*Delegating=*/false, curAddr, E,
  1686. AggValueSlot::DoesNotOverlap, NewPointerIsChecked);
  1687. }
  1688. // Go to the next element.
  1689. llvm::Value *next =
  1690. Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
  1691. "arrayctor.next");
  1692. cur->addIncoming(next, Builder.GetInsertBlock());
  1693. // Check whether that's the end of the loop.
  1694. llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
  1695. llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
  1696. Builder.CreateCondBr(done, contBB, loopBB);
  1697. // Patch the earlier check to skip over the loop.
  1698. if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
  1699. EmitBlock(contBB);
  1700. }
  1701. void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
  1702. Address addr,
  1703. QualType type) {
  1704. const RecordType *rtype = type->castAs<RecordType>();
  1705. const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
  1706. const CXXDestructorDecl *dtor = record->getDestructor();
  1707. assert(!dtor->isTrivial());
  1708. CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
  1709. /*Delegating=*/false, addr);
  1710. }
  1711. void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1712. CXXCtorType Type,
  1713. bool ForVirtualBase,
  1714. bool Delegating, Address This,
  1715. const CXXConstructExpr *E,
  1716. AggValueSlot::Overlap_t Overlap,
  1717. bool NewPointerIsChecked) {
  1718. CallArgList Args;
  1719. // Push the this ptr.
  1720. Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
  1721. // If this is a trivial constructor, emit a memcpy now before we lose
  1722. // the alignment information on the argument.
  1723. // FIXME: It would be better to preserve alignment information into CallArg.
  1724. if (isMemcpyEquivalentSpecialMember(D)) {
  1725. assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
  1726. const Expr *Arg = E->getArg(0);
  1727. LValue Src = EmitLValue(Arg);
  1728. QualType DestTy = getContext().getTypeDeclType(D->getParent());
  1729. LValue Dest = MakeAddrLValue(This, DestTy);
  1730. EmitAggregateCopyCtor(Dest, Src, Overlap);
  1731. return;
  1732. }
  1733. // Add the rest of the user-supplied arguments.
  1734. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1735. EvaluationOrder Order = E->isListInitialization()
  1736. ? EvaluationOrder::ForceLeftToRight
  1737. : EvaluationOrder::Default;
  1738. EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
  1739. /*ParamsToSkip*/ 0, Order);
  1740. EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
  1741. Overlap, E->getExprLoc(), NewPointerIsChecked);
  1742. }
  1743. static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
  1744. const CXXConstructorDecl *Ctor,
  1745. CXXCtorType Type, CallArgList &Args) {
  1746. // We can't forward a variadic call.
  1747. if (Ctor->isVariadic())
  1748. return false;
  1749. if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  1750. // If the parameters are callee-cleanup, it's not safe to forward.
  1751. for (auto *P : Ctor->parameters())
  1752. if (P->getType().isDestructedType())
  1753. return false;
  1754. // Likewise if they're inalloca.
  1755. const CGFunctionInfo &Info =
  1756. CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
  1757. if (Info.usesInAlloca())
  1758. return false;
  1759. }
  1760. // Anything else should be OK.
  1761. return true;
  1762. }
  1763. void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1764. CXXCtorType Type,
  1765. bool ForVirtualBase,
  1766. bool Delegating,
  1767. Address This,
  1768. CallArgList &Args,
  1769. AggValueSlot::Overlap_t Overlap,
  1770. SourceLocation Loc,
  1771. bool NewPointerIsChecked) {
  1772. const CXXRecordDecl *ClassDecl = D->getParent();
  1773. if (!NewPointerIsChecked)
  1774. EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
  1775. getContext().getRecordType(ClassDecl), CharUnits::Zero());
  1776. if (D->isTrivial() && D->isDefaultConstructor()) {
  1777. assert(Args.size() == 1 && "trivial default ctor with args");
  1778. return;
  1779. }
  1780. // If this is a trivial constructor, just emit what's needed. If this is a
  1781. // union copy constructor, we must emit a memcpy, because the AST does not
  1782. // model that copy.
  1783. if (isMemcpyEquivalentSpecialMember(D)) {
  1784. assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
  1785. QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
  1786. Address Src(Args[1].getRValue(*this).getScalarVal(),
  1787. getNaturalTypeAlignment(SrcTy));
  1788. LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
  1789. QualType DestTy = getContext().getTypeDeclType(ClassDecl);
  1790. LValue DestLVal = MakeAddrLValue(This, DestTy);
  1791. EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
  1792. return;
  1793. }
  1794. bool PassPrototypeArgs = true;
  1795. // Check whether we can actually emit the constructor before trying to do so.
  1796. if (auto Inherited = D->getInheritedConstructor()) {
  1797. PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
  1798. if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
  1799. EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
  1800. Delegating, Args);
  1801. return;
  1802. }
  1803. }
  1804. // Insert any ABI-specific implicit constructor arguments.
  1805. CGCXXABI::AddedStructorArgs ExtraArgs =
  1806. CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
  1807. Delegating, Args);
  1808. // Emit the call.
  1809. llvm::Constant *CalleePtr =
  1810. CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
  1811. const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
  1812. Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
  1813. CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
  1814. EmitCall(Info, Callee, ReturnValueSlot(), Args);
  1815. // Generate vtable assumptions if we're constructing a complete object
  1816. // with a vtable. We don't do this for base subobjects for two reasons:
  1817. // first, it's incorrect for classes with virtual bases, and second, we're
  1818. // about to overwrite the vptrs anyway.
  1819. // We also have to make sure if we can refer to vtable:
  1820. // - Otherwise we can refer to vtable if it's safe to speculatively emit.
  1821. // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
  1822. // sure that definition of vtable is not hidden,
  1823. // then we are always safe to refer to it.
  1824. // FIXME: It looks like InstCombine is very inefficient on dealing with
  1825. // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
  1826. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1827. ClassDecl->isDynamicClass() && Type != Ctor_Base &&
  1828. CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
  1829. CGM.getCodeGenOpts().StrictVTablePointers)
  1830. EmitVTableAssumptionLoads(ClassDecl, This);
  1831. }
  1832. void CodeGenFunction::EmitInheritedCXXConstructorCall(
  1833. const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
  1834. bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
  1835. CallArgList Args;
  1836. CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()));
  1837. // Forward the parameters.
  1838. if (InheritedFromVBase &&
  1839. CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  1840. // Nothing to do; this construction is not responsible for constructing
  1841. // the base class containing the inherited constructor.
  1842. // FIXME: Can we just pass undef's for the remaining arguments if we don't
  1843. // have constructor variants?
  1844. Args.push_back(ThisArg);
  1845. } else if (!CXXInheritedCtorInitExprArgs.empty()) {
  1846. // The inheriting constructor was inlined; just inject its arguments.
  1847. assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
  1848. "wrong number of parameters for inherited constructor call");
  1849. Args = CXXInheritedCtorInitExprArgs;
  1850. Args[0] = ThisArg;
  1851. } else {
  1852. // The inheriting constructor was not inlined. Emit delegating arguments.
  1853. Args.push_back(ThisArg);
  1854. const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
  1855. assert(OuterCtor->getNumParams() == D->getNumParams());
  1856. assert(!OuterCtor->isVariadic() && "should have been inlined");
  1857. for (const auto *Param : OuterCtor->parameters()) {
  1858. assert(getContext().hasSameUnqualifiedType(
  1859. OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
  1860. Param->getType()));
  1861. EmitDelegateCallArg(Args, Param, E->getLocation());
  1862. // Forward __attribute__(pass_object_size).
  1863. if (Param->hasAttr<PassObjectSizeAttr>()) {
  1864. auto *POSParam = SizeArguments[Param];
  1865. assert(POSParam && "missing pass_object_size value for forwarding");
  1866. EmitDelegateCallArg(Args, POSParam, E->getLocation());
  1867. }
  1868. }
  1869. }
  1870. EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
  1871. This, Args, AggValueSlot::MayOverlap,
  1872. E->getLocation(), /*NewPointerIsChecked*/true);
  1873. }
  1874. void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
  1875. const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
  1876. bool Delegating, CallArgList &Args) {
  1877. GlobalDecl GD(Ctor, CtorType);
  1878. InlinedInheritingConstructorScope Scope(*this, GD);
  1879. ApplyInlineDebugLocation DebugScope(*this, GD);
  1880. // Save the arguments to be passed to the inherited constructor.
  1881. CXXInheritedCtorInitExprArgs = Args;
  1882. FunctionArgList Params;
  1883. QualType RetType = BuildFunctionArgList(CurGD, Params);
  1884. FnRetTy = RetType;
  1885. // Insert any ABI-specific implicit constructor arguments.
  1886. CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
  1887. ForVirtualBase, Delegating, Args);
  1888. // Emit a simplified prolog. We only need to emit the implicit params.
  1889. assert(Args.size() >= Params.size() && "too few arguments for call");
  1890. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  1891. if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
  1892. const RValue &RV = Args[I].getRValue(*this);
  1893. assert(!RV.isComplex() && "complex indirect params not supported");
  1894. ParamValue Val = RV.isScalar()
  1895. ? ParamValue::forDirect(RV.getScalarVal())
  1896. : ParamValue::forIndirect(RV.getAggregateAddress());
  1897. EmitParmDecl(*Params[I], Val, I + 1);
  1898. }
  1899. }
  1900. // Create a return value slot if the ABI implementation wants one.
  1901. // FIXME: This is dumb, we should ask the ABI not to try to set the return
  1902. // value instead.
  1903. if (!RetType->isVoidType())
  1904. ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
  1905. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  1906. CXXThisValue = CXXABIThisValue;
  1907. // Directly emit the constructor initializers.
  1908. EmitCtorPrologue(Ctor, CtorType, Params);
  1909. }
  1910. void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
  1911. llvm::Value *VTableGlobal =
  1912. CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
  1913. if (!VTableGlobal)
  1914. return;
  1915. // We can just use the base offset in the complete class.
  1916. CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
  1917. if (!NonVirtualOffset.isZero())
  1918. This =
  1919. ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
  1920. Vptr.VTableClass, Vptr.NearestVBase);
  1921. llvm::Value *VPtrValue =
  1922. GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
  1923. llvm::Value *Cmp =
  1924. Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
  1925. Builder.CreateAssumption(Cmp);
  1926. }
  1927. void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
  1928. Address This) {
  1929. if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
  1930. for (const VPtr &Vptr : getVTablePointers(ClassDecl))
  1931. EmitVTableAssumptionLoad(Vptr, This);
  1932. }
  1933. void
  1934. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1935. Address This, Address Src,
  1936. const CXXConstructExpr *E) {
  1937. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1938. CallArgList Args;
  1939. // Push the this ptr.
  1940. Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
  1941. // Push the src ptr.
  1942. QualType QT = *(FPT->param_type_begin());
  1943. llvm::Type *t = CGM.getTypes().ConvertType(QT);
  1944. Src = Builder.CreateBitCast(Src, t);
  1945. Args.add(RValue::get(Src.getPointer()), QT);
  1946. // Skip over first argument (Src).
  1947. EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
  1948. /*ParamsToSkip*/ 1);
  1949. EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
  1950. /*Delegating*/false, This, Args,
  1951. AggValueSlot::MayOverlap, E->getExprLoc(),
  1952. /*NewPointerIsChecked*/false);
  1953. }
  1954. void
  1955. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1956. CXXCtorType CtorType,
  1957. const FunctionArgList &Args,
  1958. SourceLocation Loc) {
  1959. CallArgList DelegateArgs;
  1960. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  1961. assert(I != E && "no parameters to constructor");
  1962. // this
  1963. Address This = LoadCXXThisAddress();
  1964. DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
  1965. ++I;
  1966. // FIXME: The location of the VTT parameter in the parameter list is
  1967. // specific to the Itanium ABI and shouldn't be hardcoded here.
  1968. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  1969. assert(I != E && "cannot skip vtt parameter, already done with args");
  1970. assert((*I)->getType()->isPointerType() &&
  1971. "skipping parameter not of vtt type");
  1972. ++I;
  1973. }
  1974. // Explicit arguments.
  1975. for (; I != E; ++I) {
  1976. const VarDecl *param = *I;
  1977. // FIXME: per-argument source location
  1978. EmitDelegateCallArg(DelegateArgs, param, Loc);
  1979. }
  1980. EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
  1981. /*Delegating=*/true, This, DelegateArgs,
  1982. AggValueSlot::MayOverlap, Loc,
  1983. /*NewPointerIsChecked=*/true);
  1984. }
  1985. namespace {
  1986. struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
  1987. const CXXDestructorDecl *Dtor;
  1988. Address Addr;
  1989. CXXDtorType Type;
  1990. CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
  1991. CXXDtorType Type)
  1992. : Dtor(D), Addr(Addr), Type(Type) {}
  1993. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1994. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  1995. /*Delegating=*/true, Addr);
  1996. }
  1997. };
  1998. } // end anonymous namespace
  1999. void
  2000. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2001. const FunctionArgList &Args) {
  2002. assert(Ctor->isDelegatingConstructor());
  2003. Address ThisPtr = LoadCXXThisAddress();
  2004. AggValueSlot AggSlot =
  2005. AggValueSlot::forAddr(ThisPtr, Qualifiers(),
  2006. AggValueSlot::IsDestructed,
  2007. AggValueSlot::DoesNotNeedGCBarriers,
  2008. AggValueSlot::IsNotAliased,
  2009. AggValueSlot::MayOverlap,
  2010. AggValueSlot::IsNotZeroed,
  2011. // Checks are made by the code that calls constructor.
  2012. AggValueSlot::IsSanitizerChecked);
  2013. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  2014. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  2015. if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  2016. CXXDtorType Type =
  2017. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  2018. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  2019. ClassDecl->getDestructor(),
  2020. ThisPtr, Type);
  2021. }
  2022. }
  2023. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  2024. CXXDtorType Type,
  2025. bool ForVirtualBase,
  2026. bool Delegating,
  2027. Address This) {
  2028. CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
  2029. Delegating, This);
  2030. }
  2031. namespace {
  2032. struct CallLocalDtor final : EHScopeStack::Cleanup {
  2033. const CXXDestructorDecl *Dtor;
  2034. Address Addr;
  2035. CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
  2036. : Dtor(D), Addr(Addr) {}
  2037. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2038. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  2039. /*ForVirtualBase=*/false,
  2040. /*Delegating=*/false, Addr);
  2041. }
  2042. };
  2043. } // end anonymous namespace
  2044. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  2045. Address Addr) {
  2046. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
  2047. }
  2048. void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
  2049. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  2050. if (!ClassDecl) return;
  2051. if (ClassDecl->hasTrivialDestructor()) return;
  2052. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  2053. assert(D && D->isUsed() && "destructor not marked as used!");
  2054. PushDestructorCleanup(D, Addr);
  2055. }
  2056. void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
  2057. // Compute the address point.
  2058. llvm::Value *VTableAddressPoint =
  2059. CGM.getCXXABI().getVTableAddressPointInStructor(
  2060. *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
  2061. if (!VTableAddressPoint)
  2062. return;
  2063. // Compute where to store the address point.
  2064. llvm::Value *VirtualOffset = nullptr;
  2065. CharUnits NonVirtualOffset = CharUnits::Zero();
  2066. if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
  2067. // We need to use the virtual base offset offset because the virtual base
  2068. // might have a different offset in the most derived class.
  2069. VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
  2070. *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
  2071. NonVirtualOffset = Vptr.OffsetFromNearestVBase;
  2072. } else {
  2073. // We can just use the base offset in the complete class.
  2074. NonVirtualOffset = Vptr.Base.getBaseOffset();
  2075. }
  2076. // Apply the offsets.
  2077. Address VTableField = LoadCXXThisAddress();
  2078. if (!NonVirtualOffset.isZero() || VirtualOffset)
  2079. VTableField = ApplyNonVirtualAndVirtualOffset(
  2080. *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
  2081. Vptr.NearestVBase);
  2082. // Finally, store the address point. Use the same LLVM types as the field to
  2083. // support optimization.
  2084. llvm::Type *VTablePtrTy =
  2085. llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
  2086. ->getPointerTo()
  2087. ->getPointerTo();
  2088. VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
  2089. VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
  2090. llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
  2091. TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
  2092. CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
  2093. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  2094. CGM.getCodeGenOpts().StrictVTablePointers)
  2095. CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
  2096. }
  2097. CodeGenFunction::VPtrsVector
  2098. CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
  2099. CodeGenFunction::VPtrsVector VPtrsResult;
  2100. VisitedVirtualBasesSetTy VBases;
  2101. getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
  2102. /*NearestVBase=*/nullptr,
  2103. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  2104. /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
  2105. VPtrsResult);
  2106. return VPtrsResult;
  2107. }
  2108. void CodeGenFunction::getVTablePointers(BaseSubobject Base,
  2109. const CXXRecordDecl *NearestVBase,
  2110. CharUnits OffsetFromNearestVBase,
  2111. bool BaseIsNonVirtualPrimaryBase,
  2112. const CXXRecordDecl *VTableClass,
  2113. VisitedVirtualBasesSetTy &VBases,
  2114. VPtrsVector &Vptrs) {
  2115. // If this base is a non-virtual primary base the address point has already
  2116. // been set.
  2117. if (!BaseIsNonVirtualPrimaryBase) {
  2118. // Initialize the vtable pointer for this base.
  2119. VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
  2120. Vptrs.push_back(Vptr);
  2121. }
  2122. const CXXRecordDecl *RD = Base.getBase();
  2123. // Traverse bases.
  2124. for (const auto &I : RD->bases()) {
  2125. CXXRecordDecl *BaseDecl
  2126. = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  2127. // Ignore classes without a vtable.
  2128. if (!BaseDecl->isDynamicClass())
  2129. continue;
  2130. CharUnits BaseOffset;
  2131. CharUnits BaseOffsetFromNearestVBase;
  2132. bool BaseDeclIsNonVirtualPrimaryBase;
  2133. if (I.isVirtual()) {
  2134. // Check if we've visited this virtual base before.
  2135. if (!VBases.insert(BaseDecl).second)
  2136. continue;
  2137. const ASTRecordLayout &Layout =
  2138. getContext().getASTRecordLayout(VTableClass);
  2139. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  2140. BaseOffsetFromNearestVBase = CharUnits::Zero();
  2141. BaseDeclIsNonVirtualPrimaryBase = false;
  2142. } else {
  2143. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  2144. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  2145. BaseOffsetFromNearestVBase =
  2146. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  2147. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  2148. }
  2149. getVTablePointers(
  2150. BaseSubobject(BaseDecl, BaseOffset),
  2151. I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
  2152. BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
  2153. }
  2154. }
  2155. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  2156. // Ignore classes without a vtable.
  2157. if (!RD->isDynamicClass())
  2158. return;
  2159. // Initialize the vtable pointers for this class and all of its bases.
  2160. if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
  2161. for (const VPtr &Vptr : getVTablePointers(RD))
  2162. InitializeVTablePointer(Vptr);
  2163. if (RD->getNumVBases())
  2164. CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
  2165. }
  2166. llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
  2167. llvm::Type *VTableTy,
  2168. const CXXRecordDecl *RD) {
  2169. Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
  2170. llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
  2171. TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
  2172. CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
  2173. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  2174. CGM.getCodeGenOpts().StrictVTablePointers)
  2175. CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
  2176. return VTable;
  2177. }
  2178. // If a class has a single non-virtual base and does not introduce or override
  2179. // virtual member functions or fields, it will have the same layout as its base.
  2180. // This function returns the least derived such class.
  2181. //
  2182. // Casting an instance of a base class to such a derived class is technically
  2183. // undefined behavior, but it is a relatively common hack for introducing member
  2184. // functions on class instances with specific properties (e.g. llvm::Operator)
  2185. // that works under most compilers and should not have security implications, so
  2186. // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
  2187. static const CXXRecordDecl *
  2188. LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
  2189. if (!RD->field_empty())
  2190. return RD;
  2191. if (RD->getNumVBases() != 0)
  2192. return RD;
  2193. if (RD->getNumBases() != 1)
  2194. return RD;
  2195. for (const CXXMethodDecl *MD : RD->methods()) {
  2196. if (MD->isVirtual()) {
  2197. // Virtual member functions are only ok if they are implicit destructors
  2198. // because the implicit destructor will have the same semantics as the
  2199. // base class's destructor if no fields are added.
  2200. if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
  2201. continue;
  2202. return RD;
  2203. }
  2204. }
  2205. return LeastDerivedClassWithSameLayout(
  2206. RD->bases_begin()->getType()->getAsCXXRecordDecl());
  2207. }
  2208. void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
  2209. llvm::Value *VTable,
  2210. SourceLocation Loc) {
  2211. if (SanOpts.has(SanitizerKind::CFIVCall))
  2212. EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
  2213. else if (CGM.getCodeGenOpts().WholeProgramVTables &&
  2214. CGM.HasHiddenLTOVisibility(RD)) {
  2215. llvm::Metadata *MD =
  2216. CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  2217. llvm::Value *TypeId =
  2218. llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
  2219. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2220. llvm::Value *TypeTest =
  2221. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
  2222. {CastedVTable, TypeId});
  2223. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
  2224. }
  2225. }
  2226. void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
  2227. llvm::Value *VTable,
  2228. CFITypeCheckKind TCK,
  2229. SourceLocation Loc) {
  2230. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  2231. RD = LeastDerivedClassWithSameLayout(RD);
  2232. EmitVTablePtrCheck(RD, VTable, TCK, Loc);
  2233. }
  2234. void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
  2235. llvm::Value *Derived,
  2236. bool MayBeNull,
  2237. CFITypeCheckKind TCK,
  2238. SourceLocation Loc) {
  2239. if (!getLangOpts().CPlusPlus)
  2240. return;
  2241. auto *ClassTy = T->getAs<RecordType>();
  2242. if (!ClassTy)
  2243. return;
  2244. const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
  2245. if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
  2246. return;
  2247. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  2248. ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
  2249. llvm::BasicBlock *ContBlock = nullptr;
  2250. if (MayBeNull) {
  2251. llvm::Value *DerivedNotNull =
  2252. Builder.CreateIsNotNull(Derived, "cast.nonnull");
  2253. llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
  2254. ContBlock = createBasicBlock("cast.cont");
  2255. Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
  2256. EmitBlock(CheckBlock);
  2257. }
  2258. llvm::Value *VTable;
  2259. std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr(
  2260. *this, Address(Derived, getPointerAlign()), ClassDecl);
  2261. EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
  2262. if (MayBeNull) {
  2263. Builder.CreateBr(ContBlock);
  2264. EmitBlock(ContBlock);
  2265. }
  2266. }
  2267. void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
  2268. llvm::Value *VTable,
  2269. CFITypeCheckKind TCK,
  2270. SourceLocation Loc) {
  2271. if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
  2272. !CGM.HasHiddenLTOVisibility(RD))
  2273. return;
  2274. SanitizerMask M;
  2275. llvm::SanitizerStatKind SSK;
  2276. switch (TCK) {
  2277. case CFITCK_VCall:
  2278. M = SanitizerKind::CFIVCall;
  2279. SSK = llvm::SanStat_CFI_VCall;
  2280. break;
  2281. case CFITCK_NVCall:
  2282. M = SanitizerKind::CFINVCall;
  2283. SSK = llvm::SanStat_CFI_NVCall;
  2284. break;
  2285. case CFITCK_DerivedCast:
  2286. M = SanitizerKind::CFIDerivedCast;
  2287. SSK = llvm::SanStat_CFI_DerivedCast;
  2288. break;
  2289. case CFITCK_UnrelatedCast:
  2290. M = SanitizerKind::CFIUnrelatedCast;
  2291. SSK = llvm::SanStat_CFI_UnrelatedCast;
  2292. break;
  2293. case CFITCK_ICall:
  2294. case CFITCK_NVMFCall:
  2295. case CFITCK_VMFCall:
  2296. llvm_unreachable("unexpected sanitizer kind");
  2297. }
  2298. std::string TypeName = RD->getQualifiedNameAsString();
  2299. if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
  2300. return;
  2301. SanitizerScope SanScope(this);
  2302. EmitSanitizerStatReport(SSK);
  2303. llvm::Metadata *MD =
  2304. CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  2305. llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
  2306. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2307. llvm::Value *TypeTest = Builder.CreateCall(
  2308. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
  2309. llvm::Constant *StaticData[] = {
  2310. llvm::ConstantInt::get(Int8Ty, TCK),
  2311. EmitCheckSourceLocation(Loc),
  2312. EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
  2313. };
  2314. auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
  2315. if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
  2316. EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
  2317. return;
  2318. }
  2319. if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
  2320. EmitTrapCheck(TypeTest);
  2321. return;
  2322. }
  2323. llvm::Value *AllVtables = llvm::MetadataAsValue::get(
  2324. CGM.getLLVMContext(),
  2325. llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
  2326. llvm::Value *ValidVtable = Builder.CreateCall(
  2327. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
  2328. EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
  2329. StaticData, {CastedVTable, ValidVtable});
  2330. }
  2331. bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
  2332. if (!CGM.getCodeGenOpts().WholeProgramVTables ||
  2333. !SanOpts.has(SanitizerKind::CFIVCall) ||
  2334. !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
  2335. !CGM.HasHiddenLTOVisibility(RD))
  2336. return false;
  2337. std::string TypeName = RD->getQualifiedNameAsString();
  2338. return !getContext().getSanitizerBlacklist().isBlacklistedType(
  2339. SanitizerKind::CFIVCall, TypeName);
  2340. }
  2341. llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
  2342. const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
  2343. SanitizerScope SanScope(this);
  2344. EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
  2345. llvm::Metadata *MD =
  2346. CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  2347. llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
  2348. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2349. llvm::Value *CheckedLoad = Builder.CreateCall(
  2350. CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
  2351. {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
  2352. TypeId});
  2353. llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
  2354. EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
  2355. SanitizerHandler::CFICheckFail, nullptr, nullptr);
  2356. return Builder.CreateBitCast(
  2357. Builder.CreateExtractValue(CheckedLoad, 0),
  2358. cast<llvm::PointerType>(VTable->getType())->getElementType());
  2359. }
  2360. void CodeGenFunction::EmitForwardingCallToLambda(
  2361. const CXXMethodDecl *callOperator,
  2362. CallArgList &callArgs) {
  2363. // Get the address of the call operator.
  2364. const CGFunctionInfo &calleeFnInfo =
  2365. CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
  2366. llvm::Constant *calleePtr =
  2367. CGM.GetAddrOfFunction(GlobalDecl(callOperator),
  2368. CGM.getTypes().GetFunctionType(calleeFnInfo));
  2369. // Prepare the return slot.
  2370. const FunctionProtoType *FPT =
  2371. callOperator->getType()->castAs<FunctionProtoType>();
  2372. QualType resultType = FPT->getReturnType();
  2373. ReturnValueSlot returnSlot;
  2374. if (!resultType->isVoidType() &&
  2375. calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  2376. !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
  2377. returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
  2378. // We don't need to separately arrange the call arguments because
  2379. // the call can't be variadic anyway --- it's impossible to forward
  2380. // variadic arguments.
  2381. // Now emit our call.
  2382. auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
  2383. RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
  2384. // If necessary, copy the returned value into the slot.
  2385. if (!resultType->isVoidType() && returnSlot.isNull()) {
  2386. if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
  2387. RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
  2388. }
  2389. EmitReturnOfRValue(RV, resultType);
  2390. } else
  2391. EmitBranchThroughCleanup(ReturnBlock);
  2392. }
  2393. void CodeGenFunction::EmitLambdaBlockInvokeBody() {
  2394. const BlockDecl *BD = BlockInfo->getBlockDecl();
  2395. const VarDecl *variable = BD->capture_begin()->getVariable();
  2396. const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
  2397. const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  2398. if (CallOp->isVariadic()) {
  2399. // FIXME: Making this work correctly is nasty because it requires either
  2400. // cloning the body of the call operator or making the call operator
  2401. // forward.
  2402. CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
  2403. return;
  2404. }
  2405. // Start building arguments for forwarding call
  2406. CallArgList CallArgs;
  2407. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  2408. Address ThisPtr = GetAddrOfBlockDecl(variable);
  2409. CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
  2410. // Add the rest of the parameters.
  2411. for (auto param : BD->parameters())
  2412. EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
  2413. assert(!Lambda->isGenericLambda() &&
  2414. "generic lambda interconversion to block not implemented");
  2415. EmitForwardingCallToLambda(CallOp, CallArgs);
  2416. }
  2417. void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
  2418. const CXXRecordDecl *Lambda = MD->getParent();
  2419. // Start building arguments for forwarding call
  2420. CallArgList CallArgs;
  2421. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  2422. llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
  2423. CallArgs.add(RValue::get(ThisPtr), ThisType);
  2424. // Add the rest of the parameters.
  2425. for (auto Param : MD->parameters())
  2426. EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
  2427. const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  2428. // For a generic lambda, find the corresponding call operator specialization
  2429. // to which the call to the static-invoker shall be forwarded.
  2430. if (Lambda->isGenericLambda()) {
  2431. assert(MD->isFunctionTemplateSpecialization());
  2432. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  2433. FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
  2434. void *InsertPos = nullptr;
  2435. FunctionDecl *CorrespondingCallOpSpecialization =
  2436. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  2437. assert(CorrespondingCallOpSpecialization);
  2438. CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  2439. }
  2440. EmitForwardingCallToLambda(CallOp, CallArgs);
  2441. }
  2442. void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
  2443. if (MD->isVariadic()) {
  2444. // FIXME: Making this work correctly is nasty because it requires either
  2445. // cloning the body of the call operator or making the call operator forward.
  2446. CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
  2447. return;
  2448. }
  2449. EmitLambdaDelegatingInvokeBody(MD);
  2450. }