CGClass.cpp 84 KB

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