CGClass.cpp 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494
  1. //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
  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. using namespace clang;
  28. using namespace CodeGen;
  29. CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
  30. const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
  31. CastExpr::path_const_iterator End) {
  32. CharUnits Offset = CharUnits::Zero();
  33. const ASTContext &Context = getContext();
  34. const CXXRecordDecl *RD = DerivedClass;
  35. for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
  36. const CXXBaseSpecifier *Base = *I;
  37. assert(!Base->isVirtual() && "Should not see virtual bases here!");
  38. // Get the layout.
  39. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  40. const CXXRecordDecl *BaseDecl =
  41. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  42. // Add the offset.
  43. Offset += Layout.getBaseClassOffset(BaseDecl);
  44. RD = BaseDecl;
  45. }
  46. return Offset;
  47. }
  48. llvm::Constant *
  49. CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  50. CastExpr::path_const_iterator PathBegin,
  51. CastExpr::path_const_iterator PathEnd) {
  52. assert(PathBegin != PathEnd && "Base path should not be empty!");
  53. CharUnits Offset =
  54. computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
  55. if (Offset.isZero())
  56. return nullptr;
  57. llvm::Type *PtrDiffTy =
  58. Types.ConvertType(getContext().getPointerDiffType());
  59. return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
  60. }
  61. /// Gets the address of a direct base class within a complete object.
  62. /// This should only be used for (1) non-virtual bases or (2) virtual bases
  63. /// when the type is known to be complete (e.g. in complete destructors).
  64. ///
  65. /// The object pointed to by 'This' is assumed to be non-null.
  66. llvm::Value *
  67. CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
  68. const CXXRecordDecl *Derived,
  69. const CXXRecordDecl *Base,
  70. bool BaseIsVirtual) {
  71. // 'this' must be a pointer (in some address space) to Derived.
  72. assert(This->getType()->isPointerTy() &&
  73. cast<llvm::PointerType>(This->getType())->getElementType()
  74. == ConvertType(Derived));
  75. // Compute the offset of the virtual base.
  76. CharUnits Offset;
  77. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  78. if (BaseIsVirtual)
  79. Offset = Layout.getVBaseClassOffset(Base);
  80. else
  81. Offset = Layout.getBaseClassOffset(Base);
  82. // Shift and cast down to the base type.
  83. // TODO: for complete types, this should be possible with a GEP.
  84. llvm::Value *V = This;
  85. if (Offset.isPositive()) {
  86. V = Builder.CreateBitCast(V, Int8PtrTy);
  87. V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
  88. }
  89. V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
  90. return V;
  91. }
  92. static llvm::Value *
  93. ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
  94. CharUnits nonVirtualOffset,
  95. llvm::Value *virtualOffset) {
  96. // Assert that we have something to do.
  97. assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
  98. // Compute the offset from the static and dynamic components.
  99. llvm::Value *baseOffset;
  100. if (!nonVirtualOffset.isZero()) {
  101. baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
  102. nonVirtualOffset.getQuantity());
  103. if (virtualOffset) {
  104. baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
  105. }
  106. } else {
  107. baseOffset = virtualOffset;
  108. }
  109. // Apply the base offset.
  110. ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
  111. ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
  112. return ptr;
  113. }
  114. llvm::Value *CodeGenFunction::GetAddressOfBaseClass(
  115. llvm::Value *Value, const CXXRecordDecl *Derived,
  116. CastExpr::path_const_iterator PathBegin,
  117. CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
  118. SourceLocation Loc) {
  119. assert(PathBegin != PathEnd && "Base path should not be empty!");
  120. CastExpr::path_const_iterator Start = PathBegin;
  121. const CXXRecordDecl *VBase = nullptr;
  122. // Sema has done some convenient canonicalization here: if the
  123. // access path involved any virtual steps, the conversion path will
  124. // *start* with a step down to the correct virtual base subobject,
  125. // and hence will not require any further steps.
  126. if ((*Start)->isVirtual()) {
  127. VBase =
  128. cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
  129. ++Start;
  130. }
  131. // Compute the static offset of the ultimate destination within its
  132. // allocating subobject (the virtual base, if there is one, or else
  133. // the "complete" object that we see).
  134. CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
  135. VBase ? VBase : Derived, Start, PathEnd);
  136. // If there's a virtual step, we can sometimes "devirtualize" it.
  137. // For now, that's limited to when the derived type is final.
  138. // TODO: "devirtualize" this for accesses to known-complete objects.
  139. if (VBase && Derived->hasAttr<FinalAttr>()) {
  140. const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
  141. CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
  142. NonVirtualOffset += vBaseOffset;
  143. VBase = nullptr; // we no longer have a virtual step
  144. }
  145. // Get the base pointer type.
  146. llvm::Type *BasePtrTy =
  147. ConvertType((PathEnd[-1])->getType())->getPointerTo();
  148. QualType DerivedTy = getContext().getRecordType(Derived);
  149. CharUnits DerivedAlign = getContext().getTypeAlignInChars(DerivedTy);
  150. // If the static offset is zero and we don't have a virtual step,
  151. // just do a bitcast; null checks are unnecessary.
  152. if (NonVirtualOffset.isZero() && !VBase) {
  153. if (sanitizePerformTypeCheck()) {
  154. EmitTypeCheck(TCK_Upcast, Loc, Value, DerivedTy, DerivedAlign,
  155. !NullCheckValue);
  156. }
  157. return Builder.CreateBitCast(Value, BasePtrTy);
  158. }
  159. llvm::BasicBlock *origBB = nullptr;
  160. llvm::BasicBlock *endBB = nullptr;
  161. // Skip over the offset (and the vtable load) if we're supposed to
  162. // null-check the pointer.
  163. if (NullCheckValue) {
  164. origBB = Builder.GetInsertBlock();
  165. llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
  166. endBB = createBasicBlock("cast.end");
  167. llvm::Value *isNull = Builder.CreateIsNull(Value);
  168. Builder.CreateCondBr(isNull, endBB, notNullBB);
  169. EmitBlock(notNullBB);
  170. }
  171. if (sanitizePerformTypeCheck()) {
  172. EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, Value,
  173. DerivedTy, DerivedAlign, true);
  174. }
  175. // Compute the virtual offset.
  176. llvm::Value *VirtualOffset = nullptr;
  177. if (VBase) {
  178. VirtualOffset =
  179. CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
  180. }
  181. // Apply both offsets.
  182. Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
  183. NonVirtualOffset,
  184. VirtualOffset);
  185. // Cast to the destination type.
  186. Value = Builder.CreateBitCast(Value, BasePtrTy);
  187. // Build a phi if we needed a null check.
  188. if (NullCheckValue) {
  189. llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
  190. Builder.CreateBr(endBB);
  191. EmitBlock(endBB);
  192. llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
  193. PHI->addIncoming(Value, notNullBB);
  194. PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
  195. Value = PHI;
  196. }
  197. return Value;
  198. }
  199. llvm::Value *
  200. CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
  201. const CXXRecordDecl *Derived,
  202. CastExpr::path_const_iterator PathBegin,
  203. CastExpr::path_const_iterator PathEnd,
  204. bool NullCheckValue) {
  205. assert(PathBegin != PathEnd && "Base path should not be empty!");
  206. QualType DerivedTy =
  207. getContext().getCanonicalType(getContext().getTagDeclType(Derived));
  208. llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
  209. llvm::Value *NonVirtualOffset =
  210. CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
  211. if (!NonVirtualOffset) {
  212. // No offset, we can just cast back.
  213. return Builder.CreateBitCast(Value, DerivedPtrTy);
  214. }
  215. llvm::BasicBlock *CastNull = nullptr;
  216. llvm::BasicBlock *CastNotNull = nullptr;
  217. llvm::BasicBlock *CastEnd = nullptr;
  218. if (NullCheckValue) {
  219. CastNull = createBasicBlock("cast.null");
  220. CastNotNull = createBasicBlock("cast.notnull");
  221. CastEnd = createBasicBlock("cast.end");
  222. llvm::Value *IsNull = Builder.CreateIsNull(Value);
  223. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  224. EmitBlock(CastNotNull);
  225. }
  226. // Apply the offset.
  227. Value = Builder.CreateBitCast(Value, Int8PtrTy);
  228. Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
  229. "sub.ptr");
  230. // Just cast.
  231. Value = Builder.CreateBitCast(Value, DerivedPtrTy);
  232. if (NullCheckValue) {
  233. Builder.CreateBr(CastEnd);
  234. EmitBlock(CastNull);
  235. Builder.CreateBr(CastEnd);
  236. EmitBlock(CastEnd);
  237. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  238. PHI->addIncoming(Value, CastNotNull);
  239. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
  240. CastNull);
  241. Value = PHI;
  242. }
  243. return Value;
  244. }
  245. llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
  246. bool ForVirtualBase,
  247. bool Delegating) {
  248. if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
  249. // This constructor/destructor does not need a VTT parameter.
  250. return nullptr;
  251. }
  252. const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
  253. const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  254. llvm::Value *VTT;
  255. uint64_t SubVTTIndex;
  256. if (Delegating) {
  257. // If this is a delegating constructor call, just load the VTT.
  258. return LoadCXXVTT();
  259. } else if (RD == Base) {
  260. // If the record matches the base, this is the complete ctor/dtor
  261. // variant calling the base variant in a class with virtual bases.
  262. assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
  263. "doing no-op VTT offset in base dtor/ctor?");
  264. assert(!ForVirtualBase && "Can't have same class as virtual base!");
  265. SubVTTIndex = 0;
  266. } else {
  267. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  268. CharUnits BaseOffset = ForVirtualBase ?
  269. Layout.getVBaseClassOffset(Base) :
  270. Layout.getBaseClassOffset(Base);
  271. SubVTTIndex =
  272. CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
  273. assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
  274. }
  275. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  276. // A VTT parameter was passed to the constructor, use it.
  277. VTT = LoadCXXVTT();
  278. VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
  279. } else {
  280. // We're the complete constructor, so get the VTT by name.
  281. VTT = CGM.getVTables().GetAddrOfVTT(RD);
  282. VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
  283. }
  284. return VTT;
  285. }
  286. namespace {
  287. /// Call the destructor for a direct base class.
  288. struct CallBaseDtor : EHScopeStack::Cleanup {
  289. const CXXRecordDecl *BaseClass;
  290. bool BaseIsVirtual;
  291. CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
  292. : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
  293. void Emit(CodeGenFunction &CGF, Flags flags) override {
  294. const CXXRecordDecl *DerivedClass =
  295. cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
  296. const CXXDestructorDecl *D = BaseClass->getDestructor();
  297. llvm::Value *Addr =
  298. CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
  299. DerivedClass, BaseClass,
  300. BaseIsVirtual);
  301. CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
  302. /*Delegating=*/false, Addr);
  303. }
  304. };
  305. /// A visitor which checks whether an initializer uses 'this' in a
  306. /// way which requires the vtable to be properly set.
  307. struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
  308. typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
  309. bool UsesThis;
  310. DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
  311. // Black-list all explicit and implicit references to 'this'.
  312. //
  313. // Do we need to worry about external references to 'this' derived
  314. // from arbitrary code? If so, then anything which runs arbitrary
  315. // external code might potentially access the vtable.
  316. void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
  317. };
  318. }
  319. static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
  320. DynamicThisUseChecker Checker(C);
  321. Checker.Visit(Init);
  322. return Checker.UsesThis;
  323. }
  324. static void EmitBaseInitializer(CodeGenFunction &CGF,
  325. const CXXRecordDecl *ClassDecl,
  326. CXXCtorInitializer *BaseInit,
  327. CXXCtorType CtorType) {
  328. assert(BaseInit->isBaseInitializer() &&
  329. "Must have base initializer!");
  330. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  331. const Type *BaseType = BaseInit->getBaseClass();
  332. CXXRecordDecl *BaseClassDecl =
  333. cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
  334. bool isBaseVirtual = BaseInit->isBaseVirtual();
  335. // The base constructor doesn't construct virtual bases.
  336. if (CtorType == Ctor_Base && isBaseVirtual)
  337. return;
  338. // If the initializer for the base (other than the constructor
  339. // itself) accesses 'this' in any way, we need to initialize the
  340. // vtables.
  341. if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
  342. CGF.InitializeVTablePointers(ClassDecl);
  343. // We can pretend to be a complete class because it only matters for
  344. // virtual bases, and we only do virtual bases for complete ctors.
  345. llvm::Value *V =
  346. CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
  347. BaseClassDecl,
  348. isBaseVirtual);
  349. CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
  350. AggValueSlot AggSlot =
  351. AggValueSlot::forAddr(V, Alignment, Qualifiers(),
  352. AggValueSlot::IsDestructed,
  353. AggValueSlot::DoesNotNeedGCBarriers,
  354. AggValueSlot::IsNotAliased);
  355. CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
  356. if (CGF.CGM.getLangOpts().Exceptions &&
  357. !BaseClassDecl->hasTrivialDestructor())
  358. CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
  359. isBaseVirtual);
  360. }
  361. static void EmitAggMemberInitializer(CodeGenFunction &CGF,
  362. LValue LHS,
  363. Expr *Init,
  364. llvm::Value *ArrayIndexVar,
  365. QualType T,
  366. ArrayRef<VarDecl *> ArrayIndexes,
  367. unsigned Index) {
  368. if (Index == ArrayIndexes.size()) {
  369. LValue LV = LHS;
  370. if (ArrayIndexVar) {
  371. // If we have an array index variable, load it and use it as an offset.
  372. // Then, increment the value.
  373. llvm::Value *Dest = LHS.getAddress();
  374. llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
  375. Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
  376. llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
  377. Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
  378. CGF.Builder.CreateStore(Next, ArrayIndexVar);
  379. // Update the LValue.
  380. LV.setAddress(Dest);
  381. CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
  382. LV.setAlignment(std::min(Align, LV.getAlignment()));
  383. }
  384. switch (CGF.getEvaluationKind(T)) {
  385. case TEK_Scalar:
  386. CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
  387. break;
  388. case TEK_Complex:
  389. CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
  390. break;
  391. case TEK_Aggregate: {
  392. AggValueSlot Slot =
  393. AggValueSlot::forLValue(LV,
  394. AggValueSlot::IsDestructed,
  395. AggValueSlot::DoesNotNeedGCBarriers,
  396. AggValueSlot::IsNotAliased);
  397. CGF.EmitAggExpr(Init, Slot);
  398. break;
  399. }
  400. }
  401. return;
  402. }
  403. const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
  404. assert(Array && "Array initialization without the array type?");
  405. llvm::Value *IndexVar
  406. = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
  407. assert(IndexVar && "Array index variable not loaded");
  408. // Initialize this index variable to zero.
  409. llvm::Value* Zero
  410. = llvm::Constant::getNullValue(
  411. CGF.ConvertType(CGF.getContext().getSizeType()));
  412. CGF.Builder.CreateStore(Zero, IndexVar);
  413. // Start the loop with a block that tests the condition.
  414. llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
  415. llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
  416. CGF.EmitBlock(CondBlock);
  417. llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
  418. // Generate: if (loop-index < number-of-elements) fall to the loop body,
  419. // otherwise, go to the block after the for-loop.
  420. uint64_t NumElements = Array->getSize().getZExtValue();
  421. llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
  422. llvm::Value *NumElementsPtr =
  423. llvm::ConstantInt::get(Counter->getType(), NumElements);
  424. llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
  425. "isless");
  426. // If the condition is true, execute the body.
  427. CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
  428. CGF.EmitBlock(ForBody);
  429. llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
  430. // Inside the loop body recurse to emit the inner loop or, eventually, the
  431. // constructor call.
  432. EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
  433. Array->getElementType(), ArrayIndexes, Index + 1);
  434. CGF.EmitBlock(ContinueBlock);
  435. // Emit the increment of the loop counter.
  436. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
  437. Counter = CGF.Builder.CreateLoad(IndexVar);
  438. NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
  439. CGF.Builder.CreateStore(NextVal, IndexVar);
  440. // Finally, branch back up to the condition for the next iteration.
  441. CGF.EmitBranch(CondBlock);
  442. // Emit the fall-through block.
  443. CGF.EmitBlock(AfterFor, true);
  444. }
  445. static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
  446. auto *CD = dyn_cast<CXXConstructorDecl>(D);
  447. if (!(CD && CD->isCopyOrMoveConstructor()) &&
  448. !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
  449. return false;
  450. // We can emit a memcpy for a trivial copy or move constructor/assignment.
  451. if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
  452. return true;
  453. // We *must* emit a memcpy for a defaulted union copy or move op.
  454. if (D->getParent()->isUnion() && D->isDefaulted())
  455. return true;
  456. return false;
  457. }
  458. static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
  459. CXXCtorInitializer *MemberInit,
  460. LValue &LHS) {
  461. FieldDecl *Field = MemberInit->getAnyMember();
  462. if (MemberInit->isIndirectMemberInitializer()) {
  463. // If we are initializing an anonymous union field, drill down to the field.
  464. IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
  465. for (const auto *I : IndirectField->chain())
  466. LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
  467. } else {
  468. LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
  469. }
  470. }
  471. static void EmitMemberInitializer(CodeGenFunction &CGF,
  472. const CXXRecordDecl *ClassDecl,
  473. CXXCtorInitializer *MemberInit,
  474. const CXXConstructorDecl *Constructor,
  475. FunctionArgList &Args) {
  476. ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
  477. assert(MemberInit->isAnyMemberInitializer() &&
  478. "Must have member initializer!");
  479. assert(MemberInit->getInit() && "Must have initializer!");
  480. // non-static data member initializers.
  481. FieldDecl *Field = MemberInit->getAnyMember();
  482. QualType FieldType = Field->getType();
  483. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  484. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  485. LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
  486. EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
  487. // Special case: if we are in a copy or move constructor, and we are copying
  488. // an array of PODs or classes with trivial copy constructors, ignore the
  489. // AST and perform the copy we know is equivalent.
  490. // FIXME: This is hacky at best... if we had a bit more explicit information
  491. // in the AST, we could generalize it more easily.
  492. const ConstantArrayType *Array
  493. = CGF.getContext().getAsConstantArrayType(FieldType);
  494. if (Array && Constructor->isDefaulted() &&
  495. Constructor->isCopyOrMoveConstructor()) {
  496. QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
  497. CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
  498. if (BaseElementTy.isPODType(CGF.getContext()) ||
  499. (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
  500. unsigned SrcArgIndex =
  501. CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
  502. llvm::Value *SrcPtr
  503. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
  504. LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
  505. LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
  506. // Copy the aggregate.
  507. CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
  508. LHS.isVolatileQualified());
  509. // Ensure that we destroy the objects if an exception is thrown later in
  510. // the constructor.
  511. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  512. if (CGF.needsEHCleanup(dtorKind))
  513. CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
  514. return;
  515. }
  516. }
  517. ArrayRef<VarDecl *> ArrayIndexes;
  518. if (MemberInit->getNumArrayIndices())
  519. ArrayIndexes = MemberInit->getArrayIndexes();
  520. CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
  521. }
  522. void CodeGenFunction::EmitInitializerForField(
  523. FieldDecl *Field, LValue LHS, Expr *Init,
  524. ArrayRef<VarDecl *> ArrayIndexes) {
  525. QualType FieldType = Field->getType();
  526. switch (getEvaluationKind(FieldType)) {
  527. case TEK_Scalar:
  528. if (LHS.isSimple()) {
  529. EmitExprAsInit(Init, Field, LHS, false);
  530. } else {
  531. RValue RHS = RValue::get(EmitScalarExpr(Init));
  532. EmitStoreThroughLValue(RHS, LHS);
  533. }
  534. break;
  535. case TEK_Complex:
  536. EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
  537. break;
  538. case TEK_Aggregate: {
  539. llvm::Value *ArrayIndexVar = nullptr;
  540. if (ArrayIndexes.size()) {
  541. llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  542. // The LHS is a pointer to the first object we'll be constructing, as
  543. // a flat array.
  544. QualType BaseElementTy = getContext().getBaseElementType(FieldType);
  545. llvm::Type *BasePtr = ConvertType(BaseElementTy);
  546. BasePtr = llvm::PointerType::getUnqual(BasePtr);
  547. llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
  548. BasePtr);
  549. LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
  550. // Create an array index that will be used to walk over all of the
  551. // objects we're constructing.
  552. ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
  553. llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
  554. Builder.CreateStore(Zero, ArrayIndexVar);
  555. // Emit the block variables for the array indices, if any.
  556. for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
  557. EmitAutoVarDecl(*ArrayIndexes[I]);
  558. }
  559. EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
  560. ArrayIndexes, 0);
  561. }
  562. }
  563. // Ensure that we destroy this object if an exception is thrown
  564. // later in the constructor.
  565. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  566. if (needsEHCleanup(dtorKind))
  567. pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
  568. }
  569. /// Checks whether the given constructor is a valid subject for the
  570. /// complete-to-base constructor delegation optimization, i.e.
  571. /// emitting the complete constructor as a simple call to the base
  572. /// constructor.
  573. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
  574. // Currently we disable the optimization for classes with virtual
  575. // bases because (1) the addresses of parameter variables need to be
  576. // consistent across all initializers but (2) the delegate function
  577. // call necessarily creates a second copy of the parameter variable.
  578. //
  579. // The limiting example (purely theoretical AFAIK):
  580. // struct A { A(int &c) { c++; } };
  581. // struct B : virtual A {
  582. // B(int count) : A(count) { printf("%d\n", count); }
  583. // };
  584. // ...although even this example could in principle be emitted as a
  585. // delegation since the address of the parameter doesn't escape.
  586. if (Ctor->getParent()->getNumVBases()) {
  587. // TODO: white-list trivial vbase initializers. This case wouldn't
  588. // be subject to the restrictions below.
  589. // TODO: white-list cases where:
  590. // - there are no non-reference parameters to the constructor
  591. // - the initializers don't access any non-reference parameters
  592. // - the initializers don't take the address of non-reference
  593. // parameters
  594. // - etc.
  595. // If we ever add any of the above cases, remember that:
  596. // - function-try-blocks will always blacklist this optimization
  597. // - we need to perform the constructor prologue and cleanup in
  598. // EmitConstructorBody.
  599. return false;
  600. }
  601. // We also disable the optimization for variadic functions because
  602. // it's impossible to "re-pass" varargs.
  603. if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
  604. return false;
  605. // FIXME: Decide if we can do a delegation of a delegating constructor.
  606. if (Ctor->isDelegatingConstructor())
  607. return false;
  608. return true;
  609. }
  610. // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
  611. // to poison the extra field paddings inserted under
  612. // -fsanitize-address-field-padding=1|2.
  613. void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
  614. ASTContext &Context = getContext();
  615. const CXXRecordDecl *ClassDecl =
  616. Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
  617. : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
  618. if (!ClassDecl->mayInsertExtraPadding()) return;
  619. struct SizeAndOffset {
  620. uint64_t Size;
  621. uint64_t Offset;
  622. };
  623. unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
  624. const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
  625. // Populate sizes and offsets of fields.
  626. SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
  627. for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
  628. SSV[i].Offset =
  629. Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
  630. size_t NumFields = 0;
  631. for (const auto *Field : ClassDecl->fields()) {
  632. const FieldDecl *D = Field;
  633. std::pair<CharUnits, CharUnits> FieldInfo =
  634. Context.getTypeInfoInChars(D->getType());
  635. CharUnits FieldSize = FieldInfo.first;
  636. assert(NumFields < SSV.size());
  637. SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
  638. NumFields++;
  639. }
  640. assert(NumFields == SSV.size());
  641. if (SSV.size() <= 1) return;
  642. // We will insert calls to __asan_* run-time functions.
  643. // LLVM AddressSanitizer pass may decide to inline them later.
  644. llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
  645. llvm::FunctionType *FTy =
  646. llvm::FunctionType::get(CGM.VoidTy, Args, false);
  647. llvm::Constant *F = CGM.CreateRuntimeFunction(
  648. FTy, Prologue ? "__asan_poison_intra_object_redzone"
  649. : "__asan_unpoison_intra_object_redzone");
  650. llvm::Value *ThisPtr = LoadCXXThis();
  651. ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
  652. uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
  653. // For each field check if it has sufficient padding,
  654. // if so (un)poison it with a call.
  655. for (size_t i = 0; i < SSV.size(); i++) {
  656. uint64_t AsanAlignment = 8;
  657. uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
  658. uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
  659. uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
  660. if (PoisonSize < AsanAlignment || !SSV[i].Size ||
  661. (NextField % AsanAlignment) != 0)
  662. continue;
  663. Builder.CreateCall(
  664. F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
  665. Builder.getIntN(PtrSize, PoisonSize)});
  666. }
  667. }
  668. /// EmitConstructorBody - Emits the body of the current constructor.
  669. void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
  670. EmitAsanPrologueOrEpilogue(true);
  671. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
  672. CXXCtorType CtorType = CurGD.getCtorType();
  673. assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
  674. CtorType == Ctor_Complete) &&
  675. "can only generate complete ctor for this ABI");
  676. // Before we go any further, try the complete->base constructor
  677. // delegation optimization.
  678. if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
  679. CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  680. EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
  681. return;
  682. }
  683. const FunctionDecl *Definition = 0;
  684. Stmt *Body = Ctor->getBody(Definition);
  685. assert(Definition == Ctor && "emitting wrong constructor body");
  686. #if 1 // HLSL Change - no support for exception handling
  687. assert(!(Body && isa<CXXTryStmt>(Body)));
  688. #else
  689. // Enter the function-try-block before the constructor prologue if
  690. // applicable.
  691. bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
  692. if (IsTryBody)
  693. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  694. #endif // HLSL Change - no support for exception handling
  695. incrementProfileCounter(Body);
  696. RunCleanupsScope RunCleanups(*this);
  697. // TODO: in restricted cases, we can emit the vbase initializers of
  698. // a complete ctor and then delegate to the base ctor.
  699. // Emit the constructor prologue, i.e. the base and member
  700. // initializers.
  701. EmitCtorPrologue(Ctor, CtorType, Args);
  702. #if 1 // HLSL Change - no support for exception handling
  703. EmitStmt(Body);
  704. #else
  705. // Emit the body of the statement.
  706. if (IsTryBody)
  707. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  708. else if (Body)
  709. EmitStmt(Body);
  710. #endif // HLSL Change - no support for exception handling
  711. // Emit any cleanup blocks associated with the member or base
  712. // initializers, which includes (along the exceptional path) the
  713. // destructors for those members and bases that were fully
  714. // constructed.
  715. RunCleanups.ForceCleanup();
  716. #if 0 // HLSL Change - no support for exception handling
  717. if (IsTryBody)
  718. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  719. #endif // HLSL Change - no support for exception handling
  720. }
  721. namespace {
  722. /// RAII object to indicate that codegen is copying the value representation
  723. /// instead of the object representation. Useful when copying a struct or
  724. /// class which has uninitialized members and we're only performing
  725. /// lvalue-to-rvalue conversion on the object but not its members.
  726. class CopyingValueRepresentation {
  727. public:
  728. explicit CopyingValueRepresentation(CodeGenFunction &CGF)
  729. : CGF(CGF), OldSanOpts(CGF.SanOpts) {
  730. CGF.SanOpts.set(SanitizerKind::Bool, false);
  731. CGF.SanOpts.set(SanitizerKind::Enum, false);
  732. }
  733. ~CopyingValueRepresentation() {
  734. CGF.SanOpts = OldSanOpts;
  735. }
  736. private:
  737. CodeGenFunction &CGF;
  738. SanitizerSet OldSanOpts;
  739. };
  740. }
  741. namespace {
  742. class FieldMemcpyizer {
  743. public:
  744. FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
  745. const VarDecl *SrcRec)
  746. : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
  747. RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
  748. FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
  749. LastFieldOffset(0), LastAddedFieldIndex(0) {}
  750. bool isMemcpyableField(FieldDecl *F) const {
  751. // Never memcpy fields when we are adding poisoned paddings.
  752. if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
  753. return false;
  754. Qualifiers Qual = F->getType().getQualifiers();
  755. if (Qual.hasVolatile() || Qual.hasObjCLifetime())
  756. return false;
  757. return true;
  758. }
  759. void addMemcpyableField(FieldDecl *F) {
  760. if (!FirstField)
  761. addInitialField(F);
  762. else
  763. addNextField(F);
  764. }
  765. CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
  766. unsigned LastFieldSize =
  767. LastField->isBitField() ?
  768. LastField->getBitWidthValue(CGF.getContext()) :
  769. CGF.getContext().getTypeSize(LastField->getType());
  770. uint64_t MemcpySizeBits =
  771. LastFieldOffset + LastFieldSize - FirstByteOffset +
  772. CGF.getContext().getCharWidth() - 1;
  773. CharUnits MemcpySize =
  774. CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
  775. return MemcpySize;
  776. }
  777. void emitMemcpy() {
  778. // Give the subclass a chance to bail out if it feels the memcpy isn't
  779. // worth it (e.g. Hasn't aggregated enough data).
  780. if (!FirstField) {
  781. return;
  782. }
  783. uint64_t FirstByteOffset;
  784. if (FirstField->isBitField()) {
  785. const CGRecordLayout &RL =
  786. CGF.getTypes().getCGRecordLayout(FirstField->getParent());
  787. const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
  788. // FirstFieldOffset is not appropriate for bitfields,
  789. // we need to use the storage offset instead.
  790. FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
  791. } else {
  792. FirstByteOffset = FirstFieldOffset;
  793. }
  794. CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
  795. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  796. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  797. LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
  798. LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
  799. llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
  800. LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
  801. LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
  802. CharUnits Offset = CGF.getContext().toCharUnitsFromBits(FirstByteOffset);
  803. CharUnits Alignment = DestLV.getAlignment().alignmentAtOffset(Offset);
  804. emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
  805. Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
  806. MemcpySize, Alignment);
  807. reset();
  808. }
  809. void reset() {
  810. FirstField = nullptr;
  811. }
  812. protected:
  813. CodeGenFunction &CGF;
  814. const CXXRecordDecl *ClassDecl;
  815. private:
  816. void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  817. CharUnits Size, CharUnits Alignment) {
  818. llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
  819. llvm::Type *DBP =
  820. llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
  821. DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
  822. llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
  823. llvm::Type *SBP =
  824. llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
  825. SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
  826. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
  827. Alignment.getQuantity());
  828. }
  829. void addInitialField(FieldDecl *F) {
  830. FirstField = F;
  831. LastField = F;
  832. FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  833. LastFieldOffset = FirstFieldOffset;
  834. LastAddedFieldIndex = F->getFieldIndex();
  835. return;
  836. }
  837. void addNextField(FieldDecl *F) {
  838. // For the most part, the following invariant will hold:
  839. // F->getFieldIndex() == LastAddedFieldIndex + 1
  840. // The one exception is that Sema won't add a copy-initializer for an
  841. // unnamed bitfield, which will show up here as a gap in the sequence.
  842. assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
  843. "Cannot aggregate fields out of order.");
  844. LastAddedFieldIndex = F->getFieldIndex();
  845. // The 'first' and 'last' fields are chosen by offset, rather than field
  846. // index. This allows the code to support bitfields, as well as regular
  847. // fields.
  848. uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  849. if (FOffset < FirstFieldOffset) {
  850. FirstField = F;
  851. FirstFieldOffset = FOffset;
  852. } else if (FOffset > LastFieldOffset) {
  853. LastField = F;
  854. LastFieldOffset = FOffset;
  855. }
  856. }
  857. const VarDecl *SrcRec;
  858. const ASTRecordLayout &RecLayout;
  859. FieldDecl *FirstField;
  860. FieldDecl *LastField;
  861. uint64_t FirstFieldOffset, LastFieldOffset;
  862. unsigned LastAddedFieldIndex;
  863. };
  864. class ConstructorMemcpyizer : public FieldMemcpyizer {
  865. private:
  866. /// Get source argument for copy constructor. Returns null if not a copy
  867. /// constructor.
  868. static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
  869. const CXXConstructorDecl *CD,
  870. FunctionArgList &Args) {
  871. if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
  872. return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
  873. return nullptr;
  874. }
  875. // Returns true if a CXXCtorInitializer represents a member initialization
  876. // that can be rolled into a memcpy.
  877. bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
  878. if (!MemcpyableCtor)
  879. return false;
  880. FieldDecl *Field = MemberInit->getMember();
  881. assert(Field && "No field for member init.");
  882. QualType FieldType = Field->getType();
  883. CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
  884. // Bail out on non-memcpyable, not-trivially-copyable members.
  885. if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
  886. !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
  887. FieldType->isReferenceType()))
  888. return false;
  889. // Bail out on volatile fields.
  890. if (!isMemcpyableField(Field))
  891. return false;
  892. // Otherwise we're good.
  893. return true;
  894. }
  895. public:
  896. ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
  897. FunctionArgList &Args)
  898. : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
  899. ConstructorDecl(CD),
  900. MemcpyableCtor(CD->isDefaulted() &&
  901. CD->isCopyOrMoveConstructor() &&
  902. CGF.getLangOpts().getGC() == LangOptions::NonGC),
  903. Args(Args) { }
  904. void addMemberInitializer(CXXCtorInitializer *MemberInit) {
  905. if (isMemberInitMemcpyable(MemberInit)) {
  906. AggregatedInits.push_back(MemberInit);
  907. addMemcpyableField(MemberInit->getMember());
  908. } else {
  909. emitAggregatedInits();
  910. EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
  911. ConstructorDecl, Args);
  912. }
  913. }
  914. void emitAggregatedInits() {
  915. if (AggregatedInits.size() <= 1) {
  916. // This memcpy is too small to be worthwhile. Fall back on default
  917. // codegen.
  918. if (!AggregatedInits.empty()) {
  919. CopyingValueRepresentation CVR(CGF);
  920. EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
  921. AggregatedInits[0], ConstructorDecl, Args);
  922. AggregatedInits.clear();
  923. }
  924. reset();
  925. return;
  926. }
  927. pushEHDestructors();
  928. emitMemcpy();
  929. AggregatedInits.clear();
  930. }
  931. void pushEHDestructors() {
  932. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  933. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  934. LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
  935. for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
  936. CXXCtorInitializer *MemberInit = AggregatedInits[i];
  937. QualType FieldType = MemberInit->getAnyMember()->getType();
  938. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  939. if (!CGF.needsEHCleanup(dtorKind))
  940. continue;
  941. LValue FieldLHS = LHS;
  942. EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
  943. CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
  944. }
  945. }
  946. void finish() {
  947. emitAggregatedInits();
  948. }
  949. private:
  950. const CXXConstructorDecl *ConstructorDecl;
  951. bool MemcpyableCtor;
  952. FunctionArgList &Args;
  953. SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
  954. };
  955. class AssignmentMemcpyizer : public FieldMemcpyizer {
  956. private:
  957. // Returns the memcpyable field copied by the given statement, if one
  958. // exists. Otherwise returns null.
  959. FieldDecl *getMemcpyableField(Stmt *S) {
  960. if (!AssignmentsMemcpyable)
  961. return nullptr;
  962. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
  963. // Recognise trivial assignments.
  964. if (BO->getOpcode() != BO_Assign)
  965. return nullptr;
  966. MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
  967. if (!ME)
  968. return nullptr;
  969. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  970. if (!Field || !isMemcpyableField(Field))
  971. return nullptr;
  972. Stmt *RHS = BO->getRHS();
  973. if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
  974. RHS = EC->getSubExpr();
  975. if (!RHS)
  976. return nullptr;
  977. MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
  978. if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
  979. return nullptr;
  980. return Field;
  981. } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
  982. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
  983. if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
  984. return nullptr;
  985. MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
  986. if (!IOA)
  987. return nullptr;
  988. FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
  989. if (!Field || !isMemcpyableField(Field))
  990. return nullptr;
  991. MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
  992. if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
  993. return nullptr;
  994. return Field;
  995. } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  996. FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
  997. if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
  998. return nullptr;
  999. Expr *DstPtr = CE->getArg(0);
  1000. if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
  1001. DstPtr = DC->getSubExpr();
  1002. UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
  1003. if (!DUO || DUO->getOpcode() != UO_AddrOf)
  1004. return nullptr;
  1005. MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
  1006. if (!ME)
  1007. return nullptr;
  1008. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  1009. if (!Field || !isMemcpyableField(Field))
  1010. return nullptr;
  1011. Expr *SrcPtr = CE->getArg(1);
  1012. if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
  1013. SrcPtr = SC->getSubExpr();
  1014. UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
  1015. if (!SUO || SUO->getOpcode() != UO_AddrOf)
  1016. return nullptr;
  1017. MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
  1018. if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
  1019. return nullptr;
  1020. return Field;
  1021. }
  1022. return nullptr;
  1023. }
  1024. bool AssignmentsMemcpyable;
  1025. SmallVector<Stmt*, 16> AggregatedStmts;
  1026. public:
  1027. AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
  1028. FunctionArgList &Args)
  1029. : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
  1030. AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
  1031. assert(Args.size() == 2);
  1032. }
  1033. void emitAssignment(Stmt *S) {
  1034. FieldDecl *F = getMemcpyableField(S);
  1035. if (F) {
  1036. addMemcpyableField(F);
  1037. AggregatedStmts.push_back(S);
  1038. } else {
  1039. emitAggregatedStmts();
  1040. CGF.EmitStmt(S);
  1041. }
  1042. }
  1043. void emitAggregatedStmts() {
  1044. if (AggregatedStmts.size() <= 1) {
  1045. if (!AggregatedStmts.empty()) {
  1046. CopyingValueRepresentation CVR(CGF);
  1047. CGF.EmitStmt(AggregatedStmts[0]);
  1048. }
  1049. reset();
  1050. }
  1051. emitMemcpy();
  1052. AggregatedStmts.clear();
  1053. }
  1054. void finish() {
  1055. emitAggregatedStmts();
  1056. }
  1057. };
  1058. }
  1059. /// EmitCtorPrologue - This routine generates necessary code to initialize
  1060. /// base classes and non-static data members belonging to this constructor.
  1061. void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
  1062. CXXCtorType CtorType,
  1063. FunctionArgList &Args) {
  1064. if (CD->isDelegatingConstructor())
  1065. return EmitDelegatingCXXConstructorCall(CD, Args);
  1066. const CXXRecordDecl *ClassDecl = CD->getParent();
  1067. CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
  1068. E = CD->init_end();
  1069. llvm::BasicBlock *BaseCtorContinueBB = nullptr;
  1070. if (ClassDecl->getNumVBases() &&
  1071. !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  1072. // The ABIs that don't have constructor variants need to put a branch
  1073. // before the virtual base initialization code.
  1074. BaseCtorContinueBB =
  1075. CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
  1076. assert(BaseCtorContinueBB);
  1077. }
  1078. // Virtual base initializers first.
  1079. for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
  1080. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  1081. }
  1082. if (BaseCtorContinueBB) {
  1083. // Complete object handler should continue to the remaining initializers.
  1084. Builder.CreateBr(BaseCtorContinueBB);
  1085. EmitBlock(BaseCtorContinueBB);
  1086. }
  1087. // Then, non-virtual base initializers.
  1088. for (; B != E && (*B)->isBaseInitializer(); B++) {
  1089. assert(!(*B)->isBaseVirtual());
  1090. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  1091. }
  1092. InitializeVTablePointers(ClassDecl);
  1093. // And finally, initialize class members.
  1094. FieldConstructionScope FCS(*this, CXXThisValue);
  1095. ConstructorMemcpyizer CM(*this, CD, Args);
  1096. for (; B != E; B++) {
  1097. CXXCtorInitializer *Member = (*B);
  1098. assert(!Member->isBaseInitializer());
  1099. assert(Member->isAnyMemberInitializer() &&
  1100. "Delegating initializer on non-delegating constructor");
  1101. CM.addMemberInitializer(Member);
  1102. }
  1103. CM.finish();
  1104. }
  1105. static bool
  1106. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  1107. static bool
  1108. HasTrivialDestructorBody(ASTContext &Context,
  1109. const CXXRecordDecl *BaseClassDecl,
  1110. const CXXRecordDecl *MostDerivedClassDecl)
  1111. {
  1112. // If the destructor is trivial we don't have to check anything else.
  1113. if (BaseClassDecl->hasTrivialDestructor())
  1114. return true;
  1115. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  1116. return false;
  1117. // Check fields.
  1118. for (const auto *Field : BaseClassDecl->fields())
  1119. if (!FieldHasTrivialDestructorBody(Context, Field))
  1120. return false;
  1121. // Check non-virtual bases.
  1122. for (const auto &I : BaseClassDecl->bases()) {
  1123. if (I.isVirtual())
  1124. continue;
  1125. const CXXRecordDecl *NonVirtualBase =
  1126. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1127. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  1128. MostDerivedClassDecl))
  1129. return false;
  1130. }
  1131. if (BaseClassDecl == MostDerivedClassDecl) {
  1132. // Check virtual bases.
  1133. for (const auto &I : BaseClassDecl->vbases()) {
  1134. const CXXRecordDecl *VirtualBase =
  1135. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1136. if (!HasTrivialDestructorBody(Context, VirtualBase,
  1137. MostDerivedClassDecl))
  1138. return false;
  1139. }
  1140. }
  1141. return true;
  1142. }
  1143. static bool
  1144. FieldHasTrivialDestructorBody(ASTContext &Context,
  1145. const FieldDecl *Field)
  1146. {
  1147. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  1148. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  1149. if (!RT)
  1150. return true;
  1151. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  1152. // The destructor for an implicit anonymous union member is never invoked.
  1153. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  1154. return false;
  1155. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  1156. }
  1157. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  1158. /// any vtable pointers before calling this destructor.
  1159. static bool CanSkipVTablePointerInitialization(ASTContext &Context,
  1160. const CXXDestructorDecl *Dtor) {
  1161. if (!Dtor->hasTrivialBody())
  1162. return false;
  1163. // Check the fields.
  1164. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1165. for (const auto *Field : ClassDecl->fields())
  1166. if (!FieldHasTrivialDestructorBody(Context, Field))
  1167. return false;
  1168. return true;
  1169. }
  1170. // Generates function call for handling object poisoning, passing in
  1171. // references to 'this' and its size as arguments.
  1172. static void EmitDtorSanitizerCallback(CodeGenFunction &CGF,
  1173. const CXXDestructorDecl *Dtor) {
  1174. const ASTRecordLayout &Layout =
  1175. CGF.getContext().getASTRecordLayout(Dtor->getParent());
  1176. llvm::Value *Args[] = {
  1177. CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.VoidPtrTy),
  1178. llvm::ConstantInt::get(CGF.SizeTy, Layout.getSize().getQuantity())};
  1179. llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
  1180. llvm::FunctionType *FnType =
  1181. llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
  1182. llvm::Value *Fn =
  1183. CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
  1184. CGF.EmitNounwindRuntimeCall(Fn, Args);
  1185. }
  1186. /// EmitDestructorBody - Emits the body of the current destructor.
  1187. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  1188. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  1189. CXXDtorType DtorType = CurGD.getDtorType();
  1190. Stmt *Body = Dtor->getBody();
  1191. if (Body)
  1192. incrementProfileCounter(Body);
  1193. // The call to operator delete in a deleting destructor happens
  1194. // outside of the function-try-block, which means it's always
  1195. // possible to delegate the destructor body to the complete
  1196. // destructor. Do so.
  1197. if (DtorType == Dtor_Deleting) {
  1198. EnterDtorCleanups(Dtor, Dtor_Deleting);
  1199. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  1200. /*Delegating=*/false, LoadCXXThis());
  1201. PopCleanupBlock();
  1202. return;
  1203. }
  1204. #if 1 // HLSL Change - no support for exception handling
  1205. assert(!(Body && isa<CXXTryStmt>(Body)));
  1206. #else
  1207. // If the body is a function-try-block, enter the try before
  1208. // anything else.
  1209. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  1210. if (isTryBody)
  1211. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1212. #endif // HLSL Change - no support for exception handling
  1213. EmitAsanPrologueOrEpilogue(false);
  1214. // Enter the epilogue cleanups.
  1215. RunCleanupsScope DtorEpilogue(*this);
  1216. // If this is the complete variant, just invoke the base variant;
  1217. // the epilogue will destruct the virtual bases. But we can't do
  1218. // this optimization if the body is a function-try-block, because
  1219. // we'd introduce *two* handler blocks. In the Microsoft ABI, we
  1220. // always delegate because we might not have a definition in this TU.
  1221. switch (DtorType) {
  1222. case Dtor_Comdat:
  1223. llvm_unreachable("not expecting a COMDAT");
  1224. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  1225. case Dtor_Complete:
  1226. assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
  1227. "can't emit a dtor without a body for non-Microsoft ABIs");
  1228. // Enter the cleanup scopes for virtual bases.
  1229. EnterDtorCleanups(Dtor, Dtor_Complete);
  1230. #if 1 // HLSL Change - no support for exception handling
  1231. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  1232. /*Delegating=*/false, LoadCXXThis());
  1233. #else
  1234. if (!isTryBody) {
  1235. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  1236. /*Delegating=*/false, LoadCXXThis());
  1237. break;
  1238. }
  1239. #endif 1 // HLSL Change - no support for exception handling
  1240. // Fallthrough: act like we're in the base variant.
  1241. case Dtor_Base:
  1242. assert(Body);
  1243. // Enter the cleanup scopes for fields and non-virtual bases.
  1244. EnterDtorCleanups(Dtor, Dtor_Base);
  1245. // Initialize the vtable pointers before entering the body.
  1246. if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
  1247. InitializeVTablePointers(Dtor->getParent());
  1248. #if 0 // HLSL Change - no support for exception handling
  1249. if (isTryBody)
  1250. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  1251. else
  1252. #endif // HLSL Change - no support for exception handling
  1253. if (Body)
  1254. EmitStmt(Body);
  1255. else {
  1256. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  1257. // nothing to do besides what's in the epilogue
  1258. }
  1259. // -fapple-kext must inline any call to this dtor into
  1260. // the caller's body.
  1261. if (getLangOpts().AppleKext)
  1262. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  1263. break;
  1264. }
  1265. // Jump out through the epilogue cleanups.
  1266. DtorEpilogue.ForceCleanup();
  1267. // Exit the try if applicable.
  1268. #if 0 // HLSL Change - no support for exception handling
  1269. if (isTryBody)
  1270. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1271. #endif // HLSL Change - no support for exception handling
  1272. // Insert memory-poisoning instrumentation.
  1273. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor)
  1274. EmitDtorSanitizerCallback(*this, Dtor);
  1275. }
  1276. void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
  1277. const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
  1278. const Stmt *RootS = AssignOp->getBody();
  1279. assert(isa<CompoundStmt>(RootS) &&
  1280. "Body of an implicit assignment operator should be compound stmt.");
  1281. const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
  1282. LexicalScope Scope(*this, RootCS->getSourceRange());
  1283. AssignmentMemcpyizer AM(*this, AssignOp, Args);
  1284. for (auto *I : RootCS->body())
  1285. AM.emitAssignment(I);
  1286. AM.finish();
  1287. }
  1288. namespace {
  1289. /// Call the operator delete associated with the current destructor.
  1290. struct CallDtorDelete : EHScopeStack::Cleanup {
  1291. CallDtorDelete() {}
  1292. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1293. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1294. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1295. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  1296. CGF.getContext().getTagDeclType(ClassDecl));
  1297. }
  1298. };
  1299. struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
  1300. llvm::Value *ShouldDeleteCondition;
  1301. public:
  1302. CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
  1303. : ShouldDeleteCondition(ShouldDeleteCondition) {
  1304. assert(ShouldDeleteCondition != nullptr);
  1305. }
  1306. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1307. llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
  1308. llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
  1309. llvm::Value *ShouldCallDelete
  1310. = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
  1311. CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
  1312. CGF.EmitBlock(callDeleteBB);
  1313. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1314. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1315. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  1316. CGF.getContext().getTagDeclType(ClassDecl));
  1317. CGF.Builder.CreateBr(continueBB);
  1318. CGF.EmitBlock(continueBB);
  1319. }
  1320. };
  1321. class DestroyField : public EHScopeStack::Cleanup {
  1322. const FieldDecl *field;
  1323. CodeGenFunction::Destroyer *destroyer;
  1324. bool useEHCleanupForArray;
  1325. public:
  1326. DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
  1327. bool useEHCleanupForArray)
  1328. : field(field), destroyer(destroyer),
  1329. useEHCleanupForArray(useEHCleanupForArray) {}
  1330. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1331. // Find the address of the field.
  1332. llvm::Value *thisValue = CGF.LoadCXXThis();
  1333. QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
  1334. LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
  1335. LValue LV = CGF.EmitLValueForField(ThisLV, field);
  1336. assert(LV.isSimple());
  1337. CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
  1338. flags.isForNormalCleanup() && useEHCleanupForArray);
  1339. }
  1340. };
  1341. }
  1342. /// \brief Emit all code that comes at the end of class's
  1343. /// destructor. This is to call destructors on members and base classes
  1344. /// in reverse order of their construction.
  1345. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  1346. CXXDtorType DtorType) {
  1347. assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
  1348. "Should not emit dtor epilogue for non-exported trivial dtor!");
  1349. // The deleting-destructor phase just needs to call the appropriate
  1350. // operator delete that Sema picked up.
  1351. if (DtorType == Dtor_Deleting) {
  1352. assert(DD->getOperatorDelete() &&
  1353. "operator delete missing - EnterDtorCleanups");
  1354. if (CXXStructorImplicitParamValue) {
  1355. // If there is an implicit param to the deleting dtor, it's a boolean
  1356. // telling whether we should call delete at the end of the dtor.
  1357. EHStack.pushCleanup<CallDtorDeleteConditional>(
  1358. NormalAndEHCleanup, CXXStructorImplicitParamValue);
  1359. } else {
  1360. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  1361. }
  1362. return;
  1363. }
  1364. const CXXRecordDecl *ClassDecl = DD->getParent();
  1365. // Unions have no bases and do not call field destructors.
  1366. if (ClassDecl->isUnion())
  1367. return;
  1368. // The complete-destructor phase just destructs all the virtual bases.
  1369. if (DtorType == Dtor_Complete) {
  1370. // We push them in the forward order so that they'll be popped in
  1371. // the reverse order.
  1372. for (const auto &Base : ClassDecl->vbases()) {
  1373. CXXRecordDecl *BaseClassDecl
  1374. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  1375. // Ignore trivial destructors.
  1376. if (BaseClassDecl->hasTrivialDestructor())
  1377. continue;
  1378. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1379. BaseClassDecl,
  1380. /*BaseIsVirtual*/ true);
  1381. }
  1382. return;
  1383. }
  1384. assert(DtorType == Dtor_Base);
  1385. // Destroy non-virtual bases.
  1386. for (const auto &Base : ClassDecl->bases()) {
  1387. // Ignore virtual bases.
  1388. if (Base.isVirtual())
  1389. continue;
  1390. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  1391. // Ignore trivial destructors.
  1392. if (BaseClassDecl->hasTrivialDestructor())
  1393. continue;
  1394. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1395. BaseClassDecl,
  1396. /*BaseIsVirtual*/ false);
  1397. }
  1398. // Destroy direct fields.
  1399. for (const auto *Field : ClassDecl->fields()) {
  1400. QualType type = Field->getType();
  1401. QualType::DestructionKind dtorKind = type.isDestructedType();
  1402. if (!dtorKind) continue;
  1403. // Anonymous union members do not have their destructors called.
  1404. const RecordType *RT = type->getAsUnionType();
  1405. if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
  1406. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1407. EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
  1408. getDestroyer(dtorKind),
  1409. cleanupKind & EHCleanup);
  1410. }
  1411. }
  1412. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1413. /// constructor for each of several members of an array.
  1414. ///
  1415. /// \param ctor the constructor to call for each element
  1416. /// \param arrayType the type of the array to initialize
  1417. /// \param arrayBegin an arrayType*
  1418. /// \param zeroInitialize true if each element should be
  1419. /// zero-initialized before it is constructed
  1420. void CodeGenFunction::EmitCXXAggrConstructorCall(
  1421. const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
  1422. llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
  1423. QualType elementType;
  1424. llvm::Value *numElements =
  1425. emitArrayLength(arrayType, elementType, arrayBegin);
  1426. EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
  1427. }
  1428. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1429. /// constructor for each of several members of an array.
  1430. ///
  1431. /// \param ctor the constructor to call for each element
  1432. /// \param numElements the number of elements in the array;
  1433. /// may be zero
  1434. /// \param arrayBegin a T*, where T is the type constructed by ctor
  1435. /// \param zeroInitialize true if each element should be
  1436. /// zero-initialized before it is constructed
  1437. void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  1438. llvm::Value *numElements,
  1439. llvm::Value *arrayBegin,
  1440. const CXXConstructExpr *E,
  1441. bool zeroInitialize) {
  1442. // It's legal for numElements to be zero. This can happen both
  1443. // dynamically, because x can be zero in 'new A[x]', and statically,
  1444. // because of GCC extensions that permit zero-length arrays. There
  1445. // are probably legitimate places where we could assume that this
  1446. // doesn't happen, but it's not clear that it's worth it.
  1447. llvm::BranchInst *zeroCheckBranch = nullptr;
  1448. // Optimize for a constant count.
  1449. llvm::ConstantInt *constantCount
  1450. = dyn_cast<llvm::ConstantInt>(numElements);
  1451. if (constantCount) {
  1452. // Just skip out if the constant count is zero.
  1453. if (constantCount->isZero()) return;
  1454. // Otherwise, emit the check.
  1455. } else {
  1456. llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
  1457. llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
  1458. zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
  1459. EmitBlock(loopBB);
  1460. }
  1461. // Find the end of the array.
  1462. llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
  1463. "arrayctor.end");
  1464. // Enter the loop, setting up a phi for the current location to initialize.
  1465. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1466. llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
  1467. EmitBlock(loopBB);
  1468. llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
  1469. "arrayctor.cur");
  1470. cur->addIncoming(arrayBegin, entryBB);
  1471. // Inside the loop body, emit the constructor call on the array element.
  1472. QualType type = getContext().getTypeDeclType(ctor->getParent());
  1473. // Zero initialize the storage, if requested.
  1474. if (zeroInitialize)
  1475. EmitNullInitialization(cur, type);
  1476. // C++ [class.temporary]p4:
  1477. // There are two contexts in which temporaries are destroyed at a different
  1478. // point than the end of the full-expression. The first context is when a
  1479. // default constructor is called to initialize an element of an array.
  1480. // If the constructor has one or more default arguments, the destruction of
  1481. // every temporary created in a default argument expression is sequenced
  1482. // before the construction of the next array element, if any.
  1483. {
  1484. RunCleanupsScope Scope(*this);
  1485. // Evaluate the constructor and its arguments in a regular
  1486. // partial-destroy cleanup.
  1487. if (getLangOpts().Exceptions &&
  1488. !ctor->getParent()->hasTrivialDestructor()) {
  1489. Destroyer *destroyer = destroyCXXObject;
  1490. pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
  1491. }
  1492. EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
  1493. /*Delegating=*/false, cur, E);
  1494. }
  1495. // Go to the next element.
  1496. llvm::Value *next =
  1497. Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
  1498. "arrayctor.next");
  1499. cur->addIncoming(next, Builder.GetInsertBlock());
  1500. // Check whether that's the end of the loop.
  1501. llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
  1502. llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
  1503. Builder.CreateCondBr(done, contBB, loopBB);
  1504. // Patch the earlier check to skip over the loop.
  1505. if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
  1506. EmitBlock(contBB);
  1507. }
  1508. void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
  1509. llvm::Value *addr,
  1510. QualType type) {
  1511. const RecordType *rtype = type->castAs<RecordType>();
  1512. const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
  1513. const CXXDestructorDecl *dtor = record->getDestructor();
  1514. assert(!dtor->isTrivial());
  1515. CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
  1516. /*Delegating=*/false, addr);
  1517. }
  1518. void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1519. CXXCtorType Type,
  1520. bool ForVirtualBase,
  1521. bool Delegating, llvm::Value *This,
  1522. const CXXConstructExpr *E) {
  1523. // C++11 [class.mfct.non-static]p2:
  1524. // If a non-static member function of a class X is called for an object that
  1525. // is not of type X, or of a type derived from X, the behavior is undefined.
  1526. // FIXME: Provide a source location here.
  1527. EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
  1528. getContext().getRecordType(D->getParent()));
  1529. if (D->isTrivial() && D->isDefaultConstructor()) {
  1530. assert(E->getNumArgs() == 0 && "trivial default ctor with args");
  1531. return;
  1532. }
  1533. // If this is a trivial constructor, just emit what's needed. If this is a
  1534. // union copy constructor, we must emit a memcpy, because the AST does not
  1535. // model that copy.
  1536. if (isMemcpyEquivalentSpecialMember(D)) {
  1537. assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
  1538. const Expr *Arg = E->getArg(0);
  1539. QualType SrcTy = Arg->getType();
  1540. llvm::Value *Src = EmitLValue(Arg).getAddress();
  1541. QualType DestTy = getContext().getTypeDeclType(D->getParent());
  1542. EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
  1543. return;
  1544. }
  1545. CallArgList Args;
  1546. // Push the this ptr.
  1547. Args.add(RValue::get(This), D->getThisType(getContext()));
  1548. // Add the rest of the user-supplied arguments.
  1549. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1550. EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor());
  1551. // Insert any ABI-specific implicit constructor arguments.
  1552. unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
  1553. *this, D, Type, ForVirtualBase, Delegating, Args);
  1554. // Emit the call.
  1555. llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
  1556. const CGFunctionInfo &Info =
  1557. CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
  1558. EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
  1559. }
  1560. void
  1561. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1562. llvm::Value *This, llvm::Value *Src,
  1563. const CXXConstructExpr *E) {
  1564. if (isMemcpyEquivalentSpecialMember(D)) {
  1565. assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
  1566. assert(D->isCopyOrMoveConstructor() &&
  1567. "trivial 1-arg ctor not a copy/move ctor");
  1568. EmitAggregateCopyCtor(This, Src,
  1569. getContext().getTypeDeclType(D->getParent()),
  1570. E->arg_begin()->getType());
  1571. return;
  1572. }
  1573. llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
  1574. assert(D->isInstance() &&
  1575. "Trying to emit a member call expr on a static method!");
  1576. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1577. CallArgList Args;
  1578. // Push the this ptr.
  1579. Args.add(RValue::get(This), D->getThisType(getContext()));
  1580. // Push the src ptr.
  1581. QualType QT = *(FPT->param_type_begin());
  1582. llvm::Type *t = CGM.getTypes().ConvertType(QT);
  1583. Src = Builder.CreateBitCast(Src, t);
  1584. Args.add(RValue::get(Src), QT);
  1585. // Skip over first argument (Src).
  1586. EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(),
  1587. /*ParamsToSkip*/ 1);
  1588. EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
  1589. Callee, ReturnValueSlot(), Args, D);
  1590. }
  1591. void
  1592. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1593. CXXCtorType CtorType,
  1594. const FunctionArgList &Args,
  1595. SourceLocation Loc) {
  1596. CallArgList DelegateArgs;
  1597. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  1598. assert(I != E && "no parameters to constructor");
  1599. // this
  1600. DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
  1601. ++I;
  1602. // vtt
  1603. if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
  1604. /*ForVirtualBase=*/false,
  1605. /*Delegating=*/true)) {
  1606. QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
  1607. DelegateArgs.add(RValue::get(VTT), VoidPP);
  1608. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  1609. assert(I != E && "cannot skip vtt parameter, already done with args");
  1610. assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
  1611. ++I;
  1612. }
  1613. }
  1614. // Explicit arguments.
  1615. for (; I != E; ++I) {
  1616. const VarDecl *param = *I;
  1617. // FIXME: per-argument source location
  1618. EmitDelegateCallArg(DelegateArgs, param, Loc);
  1619. }
  1620. llvm::Value *Callee =
  1621. CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
  1622. EmitCall(CGM.getTypes()
  1623. .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
  1624. Callee, ReturnValueSlot(), DelegateArgs, Ctor);
  1625. }
  1626. namespace {
  1627. struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
  1628. const CXXDestructorDecl *Dtor;
  1629. llvm::Value *Addr;
  1630. CXXDtorType Type;
  1631. CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
  1632. CXXDtorType Type)
  1633. : Dtor(D), Addr(Addr), Type(Type) {}
  1634. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1635. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  1636. /*Delegating=*/true, Addr);
  1637. }
  1638. };
  1639. }
  1640. void
  1641. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1642. const FunctionArgList &Args) {
  1643. assert(Ctor->isDelegatingConstructor());
  1644. llvm::Value *ThisPtr = LoadCXXThis();
  1645. QualType Ty = getContext().getTagDeclType(Ctor->getParent());
  1646. CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
  1647. AggValueSlot AggSlot =
  1648. AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
  1649. AggValueSlot::IsDestructed,
  1650. AggValueSlot::DoesNotNeedGCBarriers,
  1651. AggValueSlot::IsNotAliased);
  1652. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  1653. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  1654. if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  1655. CXXDtorType Type =
  1656. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  1657. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  1658. ClassDecl->getDestructor(),
  1659. ThisPtr, Type);
  1660. }
  1661. }
  1662. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  1663. CXXDtorType Type,
  1664. bool ForVirtualBase,
  1665. bool Delegating,
  1666. llvm::Value *This) {
  1667. CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
  1668. Delegating, This);
  1669. }
  1670. namespace {
  1671. struct CallLocalDtor : EHScopeStack::Cleanup {
  1672. const CXXDestructorDecl *Dtor;
  1673. llvm::Value *Addr;
  1674. CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
  1675. : Dtor(D), Addr(Addr) {}
  1676. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1677. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  1678. /*ForVirtualBase=*/false,
  1679. /*Delegating=*/false, Addr);
  1680. }
  1681. };
  1682. }
  1683. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  1684. llvm::Value *Addr) {
  1685. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
  1686. }
  1687. void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
  1688. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  1689. if (!ClassDecl) return;
  1690. if (ClassDecl->hasTrivialDestructor()) return;
  1691. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  1692. assert(D && D->isUsed() && "destructor not marked as used!");
  1693. PushDestructorCleanup(D, Addr);
  1694. }
  1695. void
  1696. CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
  1697. const CXXRecordDecl *NearestVBase,
  1698. CharUnits OffsetFromNearestVBase,
  1699. const CXXRecordDecl *VTableClass) {
  1700. const CXXRecordDecl *RD = Base.getBase();
  1701. // Don't initialize the vtable pointer if the class is marked with the
  1702. // 'novtable' attribute.
  1703. if ((RD == VTableClass || RD == NearestVBase) &&
  1704. VTableClass->hasAttr<MSNoVTableAttr>())
  1705. return;
  1706. // Compute the address point.
  1707. bool NeedsVirtualOffset;
  1708. llvm::Value *VTableAddressPoint =
  1709. CGM.getCXXABI().getVTableAddressPointInStructor(
  1710. *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
  1711. if (!VTableAddressPoint)
  1712. return;
  1713. // Compute where to store the address point.
  1714. llvm::Value *VirtualOffset = nullptr;
  1715. CharUnits NonVirtualOffset = CharUnits::Zero();
  1716. if (NeedsVirtualOffset) {
  1717. // We need to use the virtual base offset offset because the virtual base
  1718. // might have a different offset in the most derived class.
  1719. VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
  1720. LoadCXXThis(),
  1721. VTableClass,
  1722. NearestVBase);
  1723. NonVirtualOffset = OffsetFromNearestVBase;
  1724. } else {
  1725. // We can just use the base offset in the complete class.
  1726. NonVirtualOffset = Base.getBaseOffset();
  1727. }
  1728. // Apply the offsets.
  1729. llvm::Value *VTableField = LoadCXXThis();
  1730. if (!NonVirtualOffset.isZero() || VirtualOffset)
  1731. VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
  1732. NonVirtualOffset,
  1733. VirtualOffset);
  1734. // Finally, store the address point. Use the same LLVM types as the field to
  1735. // support optimization.
  1736. llvm::Type *VTablePtrTy =
  1737. llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
  1738. ->getPointerTo()
  1739. ->getPointerTo();
  1740. VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
  1741. VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
  1742. llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
  1743. CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
  1744. }
  1745. void
  1746. CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
  1747. const CXXRecordDecl *NearestVBase,
  1748. CharUnits OffsetFromNearestVBase,
  1749. bool BaseIsNonVirtualPrimaryBase,
  1750. const CXXRecordDecl *VTableClass,
  1751. VisitedVirtualBasesSetTy& VBases) {
  1752. // If this base is a non-virtual primary base the address point has already
  1753. // been set.
  1754. if (!BaseIsNonVirtualPrimaryBase) {
  1755. // Initialize the vtable pointer for this base.
  1756. InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
  1757. VTableClass);
  1758. }
  1759. const CXXRecordDecl *RD = Base.getBase();
  1760. // Traverse bases.
  1761. for (const auto &I : RD->bases()) {
  1762. CXXRecordDecl *BaseDecl
  1763. = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  1764. // Ignore classes without a vtable.
  1765. if (!BaseDecl->isDynamicClass())
  1766. continue;
  1767. CharUnits BaseOffset;
  1768. CharUnits BaseOffsetFromNearestVBase;
  1769. bool BaseDeclIsNonVirtualPrimaryBase;
  1770. if (I.isVirtual()) {
  1771. // Check if we've visited this virtual base before.
  1772. if (!VBases.insert(BaseDecl).second)
  1773. continue;
  1774. const ASTRecordLayout &Layout =
  1775. getContext().getASTRecordLayout(VTableClass);
  1776. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  1777. BaseOffsetFromNearestVBase = CharUnits::Zero();
  1778. BaseDeclIsNonVirtualPrimaryBase = false;
  1779. } else {
  1780. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1781. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  1782. BaseOffsetFromNearestVBase =
  1783. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  1784. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  1785. }
  1786. InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
  1787. I.isVirtual() ? BaseDecl : NearestVBase,
  1788. BaseOffsetFromNearestVBase,
  1789. BaseDeclIsNonVirtualPrimaryBase,
  1790. VTableClass, VBases);
  1791. }
  1792. }
  1793. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  1794. // Ignore classes without a vtable.
  1795. if (!RD->isDynamicClass())
  1796. return;
  1797. // Initialize the vtable pointers for this class and all of its bases.
  1798. VisitedVirtualBasesSetTy VBases;
  1799. InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
  1800. /*NearestVBase=*/nullptr,
  1801. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  1802. /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
  1803. if (RD->getNumVBases())
  1804. CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
  1805. }
  1806. llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
  1807. llvm::Type *Ty) {
  1808. llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
  1809. llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
  1810. CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
  1811. return VTable;
  1812. }
  1813. // If a class has a single non-virtual base and does not introduce or override
  1814. // virtual member functions or fields, it will have the same layout as its base.
  1815. // This function returns the least derived such class.
  1816. //
  1817. // Casting an instance of a base class to such a derived class is technically
  1818. // undefined behavior, but it is a relatively common hack for introducing member
  1819. // functions on class instances with specific properties (e.g. llvm::Operator)
  1820. // that works under most compilers and should not have security implications, so
  1821. // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
  1822. static const CXXRecordDecl *
  1823. LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
  1824. if (!RD->field_empty())
  1825. return RD;
  1826. if (RD->getNumVBases() != 0)
  1827. return RD;
  1828. if (RD->getNumBases() != 1)
  1829. return RD;
  1830. for (const CXXMethodDecl *MD : RD->methods()) {
  1831. if (MD->isVirtual()) {
  1832. // Virtual member functions are only ok if they are implicit destructors
  1833. // because the implicit destructor will have the same semantics as the
  1834. // base class's destructor if no fields are added.
  1835. if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
  1836. continue;
  1837. return RD;
  1838. }
  1839. }
  1840. return LeastDerivedClassWithSameLayout(
  1841. RD->bases_begin()->getType()->getAsCXXRecordDecl());
  1842. }
  1843. void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
  1844. llvm::Value *VTable,
  1845. CFITypeCheckKind TCK,
  1846. SourceLocation Loc) {
  1847. const CXXRecordDecl *ClassDecl = MD->getParent();
  1848. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  1849. ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
  1850. EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
  1851. }
  1852. void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
  1853. llvm::Value *Derived,
  1854. bool MayBeNull,
  1855. CFITypeCheckKind TCK,
  1856. SourceLocation Loc) {
  1857. if (!getLangOpts().CPlusPlus)
  1858. return;
  1859. auto *ClassTy = T->getAs<RecordType>();
  1860. if (!ClassTy)
  1861. return;
  1862. const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
  1863. if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
  1864. return;
  1865. SmallString<64> MangledName;
  1866. llvm::raw_svector_ostream Out(MangledName);
  1867. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(T.getUnqualifiedType(),
  1868. Out);
  1869. // Blacklist based on the mangled type.
  1870. if (CGM.getContext().getSanitizerBlacklist().isBlacklistedType(Out.str()))
  1871. return;
  1872. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  1873. ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
  1874. llvm::BasicBlock *ContBlock = 0;
  1875. if (MayBeNull) {
  1876. llvm::Value *DerivedNotNull =
  1877. Builder.CreateIsNotNull(Derived, "cast.nonnull");
  1878. llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
  1879. ContBlock = createBasicBlock("cast.cont");
  1880. Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
  1881. EmitBlock(CheckBlock);
  1882. }
  1883. llvm::Value *VTable = GetVTablePtr(Derived, Int8PtrTy);
  1884. EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
  1885. if (MayBeNull) {
  1886. Builder.CreateBr(ContBlock);
  1887. EmitBlock(ContBlock);
  1888. }
  1889. }
  1890. void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
  1891. llvm::Value *VTable,
  1892. CFITypeCheckKind TCK,
  1893. SourceLocation Loc) {
  1894. if (CGM.IsCFIBlacklistedRecord(RD))
  1895. return;
  1896. SanitizerScope SanScope(this);
  1897. std::string OutName;
  1898. llvm::raw_string_ostream Out(OutName);
  1899. CGM.getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
  1900. llvm::Value *BitSetName = llvm::MetadataAsValue::get(
  1901. getLLVMContext(), llvm::MDString::get(getLLVMContext(), Out.str()));
  1902. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  1903. llvm::Value *BitSetTest =
  1904. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
  1905. {CastedVTable, BitSetName});
  1906. SanitizerMask M;
  1907. switch (TCK) {
  1908. case CFITCK_VCall:
  1909. M = SanitizerKind::CFIVCall;
  1910. break;
  1911. case CFITCK_NVCall:
  1912. M = SanitizerKind::CFINVCall;
  1913. break;
  1914. case CFITCK_DerivedCast:
  1915. M = SanitizerKind::CFIDerivedCast;
  1916. break;
  1917. case CFITCK_UnrelatedCast:
  1918. M = SanitizerKind::CFIUnrelatedCast;
  1919. break;
  1920. }
  1921. llvm::Constant *StaticData[] = {
  1922. EmitCheckSourceLocation(Loc),
  1923. EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
  1924. llvm::ConstantInt::get(Int8Ty, TCK),
  1925. };
  1926. EmitCheck(std::make_pair(BitSetTest, M), "cfi_bad_type", StaticData,
  1927. CastedVTable);
  1928. }
  1929. // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
  1930. // quite what we want.
  1931. static const Expr *skipNoOpCastsAndParens(const Expr *E) {
  1932. while (true) {
  1933. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  1934. E = PE->getSubExpr();
  1935. continue;
  1936. }
  1937. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1938. if (CE->getCastKind() == CK_NoOp) {
  1939. E = CE->getSubExpr();
  1940. continue;
  1941. }
  1942. }
  1943. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  1944. if (UO->getOpcode() == UO_Extension) {
  1945. E = UO->getSubExpr();
  1946. continue;
  1947. }
  1948. }
  1949. return E;
  1950. }
  1951. }
  1952. bool
  1953. CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
  1954. const CXXMethodDecl *MD) {
  1955. // When building with -fapple-kext, all calls must go through the vtable since
  1956. // the kernel linker can do runtime patching of vtables.
  1957. if (getLangOpts().AppleKext)
  1958. return false;
  1959. // If the most derived class is marked final, we know that no subclass can
  1960. // override this member function and so we can devirtualize it. For example:
  1961. //
  1962. // struct A { virtual void f(); }
  1963. // struct B final : A { };
  1964. //
  1965. // void f(B *b) {
  1966. // b->f();
  1967. // }
  1968. //
  1969. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  1970. if (MostDerivedClassDecl->hasAttr<FinalAttr>())
  1971. return true;
  1972. // If the member function is marked 'final', we know that it can't be
  1973. // overridden and can therefore devirtualize it.
  1974. if (MD->hasAttr<FinalAttr>())
  1975. return true;
  1976. // Similarly, if the class itself is marked 'final' it can't be overridden
  1977. // and we can therefore devirtualize the member function call.
  1978. if (MD->getParent()->hasAttr<FinalAttr>())
  1979. return true;
  1980. Base = skipNoOpCastsAndParens(Base);
  1981. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  1982. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  1983. // This is a record decl. We know the type and can devirtualize it.
  1984. return VD->getType()->isRecordType();
  1985. }
  1986. return false;
  1987. }
  1988. // We can devirtualize calls on an object accessed by a class member access
  1989. // expression, since by C++11 [basic.life]p6 we know that it can't refer to
  1990. // a derived class object constructed in the same location.
  1991. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
  1992. if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
  1993. return VD->getType()->isRecordType();
  1994. // We can always devirtualize calls on temporary object expressions.
  1995. if (isa<CXXConstructExpr>(Base))
  1996. return true;
  1997. // And calls on bound temporaries.
  1998. if (isa<CXXBindTemporaryExpr>(Base))
  1999. return true;
  2000. // Check if this is a call expr that returns a record type.
  2001. if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
  2002. return CE->getCallReturnType(getContext())->isRecordType();
  2003. // We can't devirtualize the call.
  2004. return false;
  2005. }
  2006. void CodeGenFunction::EmitForwardingCallToLambda(
  2007. const CXXMethodDecl *callOperator,
  2008. CallArgList &callArgs) {
  2009. // Get the address of the call operator.
  2010. const CGFunctionInfo &calleeFnInfo =
  2011. CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
  2012. llvm::Value *callee =
  2013. CGM.GetAddrOfFunction(GlobalDecl(callOperator),
  2014. CGM.getTypes().GetFunctionType(calleeFnInfo));
  2015. // Prepare the return slot.
  2016. const FunctionProtoType *FPT =
  2017. callOperator->getType()->castAs<FunctionProtoType>();
  2018. QualType resultType = FPT->getReturnType();
  2019. ReturnValueSlot returnSlot;
  2020. if (!resultType->isVoidType() &&
  2021. calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  2022. !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
  2023. returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
  2024. // We don't need to separately arrange the call arguments because
  2025. // the call can't be variadic anyway --- it's impossible to forward
  2026. // variadic arguments.
  2027. // Now emit our call.
  2028. RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
  2029. callArgs, callOperator);
  2030. // If necessary, copy the returned value into the slot.
  2031. if (!resultType->isVoidType() && returnSlot.isNull())
  2032. EmitReturnOfRValue(RV, resultType);
  2033. else
  2034. EmitBranchThroughCleanup(ReturnBlock);
  2035. }
  2036. void CodeGenFunction::EmitLambdaBlockInvokeBody() {
  2037. const BlockDecl *BD = BlockInfo->getBlockDecl();
  2038. const VarDecl *variable = BD->capture_begin()->getVariable();
  2039. const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
  2040. // Start building arguments for forwarding call
  2041. CallArgList CallArgs;
  2042. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  2043. llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
  2044. CallArgs.add(RValue::get(ThisPtr), ThisType);
  2045. // Add the rest of the parameters.
  2046. for (auto param : BD->params())
  2047. EmitDelegateCallArg(CallArgs, param, param->getLocStart());
  2048. assert(!Lambda->isGenericLambda() &&
  2049. "generic lambda interconversion to block not implemented");
  2050. EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
  2051. }
  2052. void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
  2053. if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
  2054. // FIXME: Making this work correctly is nasty because it requires either
  2055. // cloning the body of the call operator or making the call operator forward.
  2056. CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
  2057. return;
  2058. }
  2059. EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
  2060. }
  2061. void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
  2062. const CXXRecordDecl *Lambda = MD->getParent();
  2063. // Start building arguments for forwarding call
  2064. CallArgList CallArgs;
  2065. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  2066. llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
  2067. CallArgs.add(RValue::get(ThisPtr), ThisType);
  2068. // Add the rest of the parameters.
  2069. for (auto Param : MD->params())
  2070. EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
  2071. const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  2072. // For a generic lambda, find the corresponding call operator specialization
  2073. // to which the call to the static-invoker shall be forwarded.
  2074. if (Lambda->isGenericLambda()) {
  2075. assert(MD->isFunctionTemplateSpecialization());
  2076. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  2077. FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
  2078. void *InsertPos = nullptr;
  2079. FunctionDecl *CorrespondingCallOpSpecialization =
  2080. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  2081. assert(CorrespondingCallOpSpecialization);
  2082. CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  2083. }
  2084. EmitForwardingCallToLambda(CallOp, CallArgs);
  2085. }
  2086. void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
  2087. if (MD->isVariadic()) {
  2088. // FIXME: Making this work correctly is nasty because it requires either
  2089. // cloning the body of the call operator or making the call operator forward.
  2090. CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
  2091. return;
  2092. }
  2093. EmitLambdaDelegatingInvokeBody(MD);
  2094. }