CGClass.cpp 81 KB

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