CGClass.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711
  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 "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/EvaluatedExprVisitor.h"
  17. #include "clang/AST/RecordLayout.h"
  18. #include "clang/AST/StmtCXX.h"
  19. #include "clang/Frontend/CodeGenOptions.h"
  20. using namespace clang;
  21. using namespace CodeGen;
  22. static CharUnits
  23. ComputeNonVirtualBaseClassOffset(ASTContext &Context,
  24. const CXXRecordDecl *DerivedClass,
  25. CastExpr::path_const_iterator Start,
  26. CastExpr::path_const_iterator End) {
  27. CharUnits Offset = CharUnits::Zero();
  28. const CXXRecordDecl *RD = DerivedClass;
  29. for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
  30. const CXXBaseSpecifier *Base = *I;
  31. assert(!Base->isVirtual() && "Should not see virtual bases here!");
  32. // Get the layout.
  33. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  34. const CXXRecordDecl *BaseDecl =
  35. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  36. // Add the offset.
  37. Offset += Layout.getBaseClassOffset(BaseDecl);
  38. RD = BaseDecl;
  39. }
  40. return Offset;
  41. }
  42. llvm::Constant *
  43. CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  44. CastExpr::path_const_iterator PathBegin,
  45. CastExpr::path_const_iterator PathEnd) {
  46. assert(PathBegin != PathEnd && "Base path should not be empty!");
  47. CharUnits Offset =
  48. ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
  49. PathBegin, PathEnd);
  50. if (Offset.isZero())
  51. return 0;
  52. llvm::Type *PtrDiffTy =
  53. Types.ConvertType(getContext().getPointerDiffType());
  54. return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
  55. }
  56. /// Gets the address of a direct base class within a complete object.
  57. /// This should only be used for (1) non-virtual bases or (2) virtual bases
  58. /// when the type is known to be complete (e.g. in complete destructors).
  59. ///
  60. /// The object pointed to by 'This' is assumed to be non-null.
  61. llvm::Value *
  62. CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
  63. const CXXRecordDecl *Derived,
  64. const CXXRecordDecl *Base,
  65. bool BaseIsVirtual) {
  66. // 'this' must be a pointer (in some address space) to Derived.
  67. assert(This->getType()->isPointerTy() &&
  68. cast<llvm::PointerType>(This->getType())->getElementType()
  69. == ConvertType(Derived));
  70. // Compute the offset of the virtual base.
  71. CharUnits Offset;
  72. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  73. if (BaseIsVirtual)
  74. Offset = Layout.getVBaseClassOffset(Base);
  75. else
  76. Offset = Layout.getBaseClassOffset(Base);
  77. // Shift and cast down to the base type.
  78. // TODO: for complete types, this should be possible with a GEP.
  79. llvm::Value *V = This;
  80. if (Offset.isPositive()) {
  81. llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
  82. V = Builder.CreateBitCast(V, Int8PtrTy);
  83. V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
  84. }
  85. V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
  86. return V;
  87. }
  88. static llvm::Value *
  89. ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
  90. CharUnits NonVirtual, llvm::Value *Virtual) {
  91. llvm::Type *PtrDiffTy =
  92. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  93. llvm::Value *NonVirtualOffset = 0;
  94. if (!NonVirtual.isZero())
  95. NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
  96. NonVirtual.getQuantity());
  97. llvm::Value *BaseOffset;
  98. if (Virtual) {
  99. if (NonVirtualOffset)
  100. BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
  101. else
  102. BaseOffset = Virtual;
  103. } else
  104. BaseOffset = NonVirtualOffset;
  105. // Apply the base offset.
  106. llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
  107. ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
  108. ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
  109. return ThisPtr;
  110. }
  111. llvm::Value *
  112. CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
  113. const CXXRecordDecl *Derived,
  114. CastExpr::path_const_iterator PathBegin,
  115. CastExpr::path_const_iterator PathEnd,
  116. bool NullCheckValue) {
  117. assert(PathBegin != PathEnd && "Base path should not be empty!");
  118. CastExpr::path_const_iterator Start = PathBegin;
  119. const CXXRecordDecl *VBase = 0;
  120. // Get the virtual base.
  121. if ((*Start)->isVirtual()) {
  122. VBase =
  123. cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
  124. ++Start;
  125. }
  126. CharUnits NonVirtualOffset =
  127. ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
  128. Start, PathEnd);
  129. // Get the base pointer type.
  130. llvm::Type *BasePtrTy =
  131. ConvertType((PathEnd[-1])->getType())->getPointerTo();
  132. if (NonVirtualOffset.isZero() && !VBase) {
  133. // Just cast back.
  134. return Builder.CreateBitCast(Value, BasePtrTy);
  135. }
  136. llvm::BasicBlock *CastNull = 0;
  137. llvm::BasicBlock *CastNotNull = 0;
  138. llvm::BasicBlock *CastEnd = 0;
  139. if (NullCheckValue) {
  140. CastNull = createBasicBlock("cast.null");
  141. CastNotNull = createBasicBlock("cast.notnull");
  142. CastEnd = createBasicBlock("cast.end");
  143. llvm::Value *IsNull = Builder.CreateIsNull(Value);
  144. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  145. EmitBlock(CastNotNull);
  146. }
  147. llvm::Value *VirtualOffset = 0;
  148. if (VBase) {
  149. if (Derived->hasAttr<FinalAttr>()) {
  150. VirtualOffset = 0;
  151. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  152. CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
  153. NonVirtualOffset += VBaseOffset;
  154. } else
  155. VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
  156. }
  157. // Apply the offsets.
  158. Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
  159. NonVirtualOffset,
  160. VirtualOffset);
  161. // Cast back.
  162. Value = Builder.CreateBitCast(Value, BasePtrTy);
  163. if (NullCheckValue) {
  164. Builder.CreateBr(CastEnd);
  165. EmitBlock(CastNull);
  166. Builder.CreateBr(CastEnd);
  167. EmitBlock(CastEnd);
  168. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  169. PHI->addIncoming(Value, CastNotNull);
  170. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
  171. CastNull);
  172. Value = PHI;
  173. }
  174. return Value;
  175. }
  176. llvm::Value *
  177. CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
  178. const CXXRecordDecl *Derived,
  179. CastExpr::path_const_iterator PathBegin,
  180. CastExpr::path_const_iterator PathEnd,
  181. bool NullCheckValue) {
  182. assert(PathBegin != PathEnd && "Base path should not be empty!");
  183. QualType DerivedTy =
  184. getContext().getCanonicalType(getContext().getTagDeclType(Derived));
  185. llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
  186. llvm::Value *NonVirtualOffset =
  187. CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
  188. if (!NonVirtualOffset) {
  189. // No offset, we can just cast back.
  190. return Builder.CreateBitCast(Value, DerivedPtrTy);
  191. }
  192. llvm::BasicBlock *CastNull = 0;
  193. llvm::BasicBlock *CastNotNull = 0;
  194. llvm::BasicBlock *CastEnd = 0;
  195. if (NullCheckValue) {
  196. CastNull = createBasicBlock("cast.null");
  197. CastNotNull = createBasicBlock("cast.notnull");
  198. CastEnd = createBasicBlock("cast.end");
  199. llvm::Value *IsNull = Builder.CreateIsNull(Value);
  200. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  201. EmitBlock(CastNotNull);
  202. }
  203. // Apply the offset.
  204. Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
  205. Value = Builder.CreateSub(Value, NonVirtualOffset);
  206. Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
  207. // Just cast.
  208. Value = Builder.CreateBitCast(Value, DerivedPtrTy);
  209. if (NullCheckValue) {
  210. Builder.CreateBr(CastEnd);
  211. EmitBlock(CastNull);
  212. Builder.CreateBr(CastEnd);
  213. EmitBlock(CastEnd);
  214. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  215. PHI->addIncoming(Value, CastNotNull);
  216. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
  217. CastNull);
  218. Value = PHI;
  219. }
  220. return Value;
  221. }
  222. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  223. /// base constructor/destructor with virtual bases.
  224. static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
  225. bool ForVirtualBase) {
  226. if (!CodeGenVTables::needsVTTParameter(GD)) {
  227. // This constructor/destructor does not need a VTT parameter.
  228. return 0;
  229. }
  230. const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
  231. const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  232. llvm::Value *VTT;
  233. uint64_t SubVTTIndex;
  234. // If the record matches the base, this is the complete ctor/dtor
  235. // variant calling the base variant in a class with virtual bases.
  236. if (RD == Base) {
  237. assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
  238. "doing no-op VTT offset in base dtor/ctor?");
  239. assert(!ForVirtualBase && "Can't have same class as virtual base!");
  240. SubVTTIndex = 0;
  241. } else {
  242. const ASTRecordLayout &Layout =
  243. CGF.getContext().getASTRecordLayout(RD);
  244. CharUnits BaseOffset = ForVirtualBase ?
  245. Layout.getVBaseClassOffset(Base) :
  246. Layout.getBaseClassOffset(Base);
  247. SubVTTIndex =
  248. CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
  249. assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
  250. }
  251. if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
  252. // A VTT parameter was passed to the constructor, use it.
  253. VTT = CGF.LoadCXXVTT();
  254. VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
  255. } else {
  256. // We're the complete constructor, so get the VTT by name.
  257. VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
  258. VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
  259. }
  260. return VTT;
  261. }
  262. namespace {
  263. /// Call the destructor for a direct base class.
  264. struct CallBaseDtor : EHScopeStack::Cleanup {
  265. const CXXRecordDecl *BaseClass;
  266. bool BaseIsVirtual;
  267. CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
  268. : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
  269. void Emit(CodeGenFunction &CGF, Flags flags) {
  270. const CXXRecordDecl *DerivedClass =
  271. cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
  272. const CXXDestructorDecl *D = BaseClass->getDestructor();
  273. llvm::Value *Addr =
  274. CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
  275. DerivedClass, BaseClass,
  276. BaseIsVirtual);
  277. CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
  278. }
  279. };
  280. /// A visitor which checks whether an initializer uses 'this' in a
  281. /// way which requires the vtable to be properly set.
  282. struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
  283. typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
  284. bool UsesThis;
  285. DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
  286. // Black-list all explicit and implicit references to 'this'.
  287. //
  288. // Do we need to worry about external references to 'this' derived
  289. // from arbitrary code? If so, then anything which runs arbitrary
  290. // external code might potentially access the vtable.
  291. void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
  292. };
  293. }
  294. static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
  295. DynamicThisUseChecker Checker(C);
  296. Checker.Visit(const_cast<Expr*>(Init));
  297. return Checker.UsesThis;
  298. }
  299. static void EmitBaseInitializer(CodeGenFunction &CGF,
  300. const CXXRecordDecl *ClassDecl,
  301. CXXCtorInitializer *BaseInit,
  302. CXXCtorType CtorType) {
  303. assert(BaseInit->isBaseInitializer() &&
  304. "Must have base initializer!");
  305. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  306. const Type *BaseType = BaseInit->getBaseClass();
  307. CXXRecordDecl *BaseClassDecl =
  308. cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
  309. bool isBaseVirtual = BaseInit->isBaseVirtual();
  310. // The base constructor doesn't construct virtual bases.
  311. if (CtorType == Ctor_Base && isBaseVirtual)
  312. return;
  313. // If the initializer for the base (other than the constructor
  314. // itself) accesses 'this' in any way, we need to initialize the
  315. // vtables.
  316. if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
  317. CGF.InitializeVTablePointers(ClassDecl);
  318. // We can pretend to be a complete class because it only matters for
  319. // virtual bases, and we only do virtual bases for complete ctors.
  320. llvm::Value *V =
  321. CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
  322. BaseClassDecl,
  323. isBaseVirtual);
  324. CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
  325. AggValueSlot AggSlot =
  326. AggValueSlot::forAddr(V, Alignment, Qualifiers(),
  327. AggValueSlot::IsDestructed,
  328. AggValueSlot::DoesNotNeedGCBarriers,
  329. AggValueSlot::IsNotAliased);
  330. CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
  331. if (CGF.CGM.getLangOptions().Exceptions &&
  332. !BaseClassDecl->hasTrivialDestructor())
  333. CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
  334. isBaseVirtual);
  335. }
  336. static void EmitAggMemberInitializer(CodeGenFunction &CGF,
  337. LValue LHS,
  338. llvm::Value *ArrayIndexVar,
  339. CXXCtorInitializer *MemberInit,
  340. QualType T,
  341. unsigned Index) {
  342. if (Index == MemberInit->getNumArrayIndices()) {
  343. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  344. LValue LV = LHS;
  345. if (ArrayIndexVar) {
  346. // If we have an array index variable, load it and use it as an offset.
  347. // Then, increment the value.
  348. llvm::Value *Dest = LHS.getAddress();
  349. llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
  350. Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
  351. llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
  352. Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
  353. CGF.Builder.CreateStore(Next, ArrayIndexVar);
  354. // Update the LValue.
  355. LV.setAddress(Dest);
  356. CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
  357. LV.setAlignment(std::min(Align, LV.getAlignment()));
  358. }
  359. if (!CGF.hasAggregateLLVMType(T)) {
  360. CGF.EmitScalarInit(MemberInit->getInit(), /*decl*/ 0, LV, false);
  361. } else if (T->isAnyComplexType()) {
  362. CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LV.getAddress(),
  363. LV.isVolatileQualified());
  364. } else {
  365. AggValueSlot Slot =
  366. AggValueSlot::forLValue(LV,
  367. AggValueSlot::IsDestructed,
  368. AggValueSlot::DoesNotNeedGCBarriers,
  369. AggValueSlot::IsNotAliased);
  370. CGF.EmitAggExpr(MemberInit->getInit(), Slot);
  371. }
  372. return;
  373. }
  374. const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
  375. assert(Array && "Array initialization without the array type?");
  376. llvm::Value *IndexVar
  377. = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
  378. assert(IndexVar && "Array index variable not loaded");
  379. // Initialize this index variable to zero.
  380. llvm::Value* Zero
  381. = llvm::Constant::getNullValue(
  382. CGF.ConvertType(CGF.getContext().getSizeType()));
  383. CGF.Builder.CreateStore(Zero, IndexVar);
  384. // Start the loop with a block that tests the condition.
  385. llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
  386. llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
  387. CGF.EmitBlock(CondBlock);
  388. llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
  389. // Generate: if (loop-index < number-of-elements) fall to the loop body,
  390. // otherwise, go to the block after the for-loop.
  391. uint64_t NumElements = Array->getSize().getZExtValue();
  392. llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
  393. llvm::Value *NumElementsPtr =
  394. llvm::ConstantInt::get(Counter->getType(), NumElements);
  395. llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
  396. "isless");
  397. // If the condition is true, execute the body.
  398. CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
  399. CGF.EmitBlock(ForBody);
  400. llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
  401. {
  402. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  403. // Inside the loop body recurse to emit the inner loop or, eventually, the
  404. // constructor call.
  405. EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
  406. Array->getElementType(), Index + 1);
  407. }
  408. CGF.EmitBlock(ContinueBlock);
  409. // Emit the increment of the loop counter.
  410. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
  411. Counter = CGF.Builder.CreateLoad(IndexVar);
  412. NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
  413. CGF.Builder.CreateStore(NextVal, IndexVar);
  414. // Finally, branch back up to the condition for the next iteration.
  415. CGF.EmitBranch(CondBlock);
  416. // Emit the fall-through block.
  417. CGF.EmitBlock(AfterFor, true);
  418. }
  419. namespace {
  420. struct CallMemberDtor : EHScopeStack::Cleanup {
  421. FieldDecl *Field;
  422. CXXDestructorDecl *Dtor;
  423. CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
  424. : Field(Field), Dtor(Dtor) {}
  425. void Emit(CodeGenFunction &CGF, Flags flags) {
  426. // FIXME: Is this OK for C++0x delegating constructors?
  427. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  428. LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
  429. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  430. LHS.getAddress());
  431. }
  432. };
  433. }
  434. static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record,
  435. bool Moving) {
  436. return Moving ? Record->hasTrivialMoveConstructor() :
  437. Record->hasTrivialCopyConstructor();
  438. }
  439. static void EmitMemberInitializer(CodeGenFunction &CGF,
  440. const CXXRecordDecl *ClassDecl,
  441. CXXCtorInitializer *MemberInit,
  442. const CXXConstructorDecl *Constructor,
  443. FunctionArgList &Args) {
  444. assert(MemberInit->isAnyMemberInitializer() &&
  445. "Must have member initializer!");
  446. assert(MemberInit->getInit() && "Must have initializer!");
  447. // non-static data member initializers.
  448. FieldDecl *Field = MemberInit->getAnyMember();
  449. QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
  450. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  451. LValue LHS;
  452. // If we are initializing an anonymous union field, drill down to the field.
  453. if (MemberInit->isIndirectMemberInitializer()) {
  454. LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
  455. MemberInit->getIndirectMember(), 0);
  456. FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
  457. } else {
  458. LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
  459. }
  460. if (!CGF.hasAggregateLLVMType(Field->getType())) {
  461. if (LHS.isSimple()) {
  462. CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS, false);
  463. } else {
  464. RValue RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
  465. CGF.EmitStoreThroughLValue(RHS, LHS);
  466. }
  467. } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
  468. CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
  469. LHS.isVolatileQualified());
  470. } else {
  471. llvm::Value *ArrayIndexVar = 0;
  472. const ConstantArrayType *Array
  473. = CGF.getContext().getAsConstantArrayType(FieldType);
  474. if (Array && Constructor->isImplicitlyDefined() &&
  475. Constructor->isCopyOrMoveConstructor()) {
  476. llvm::Type *SizeTy
  477. = CGF.ConvertType(CGF.getContext().getSizeType());
  478. // The LHS is a pointer to the first object we'll be constructing, as
  479. // a flat array.
  480. QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
  481. llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
  482. BasePtr = llvm::PointerType::getUnqual(BasePtr);
  483. llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
  484. BasePtr);
  485. LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
  486. // Create an array index that will be used to walk over all of the
  487. // objects we're constructing.
  488. ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
  489. llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
  490. CGF.Builder.CreateStore(Zero, ArrayIndexVar);
  491. // If we are copying an array of PODs or classes with trivial copy
  492. // constructors, perform a single aggregate copy.
  493. const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
  494. if (BaseElementTy.isPODType(CGF.getContext()) ||
  495. (Record && hasTrivialCopyOrMoveConstructor(Record,
  496. Constructor->isMoveConstructor()))) {
  497. // Find the source pointer. We knows it's the last argument because
  498. // we know we're in a copy constructor.
  499. unsigned SrcArgIndex = Args.size() - 1;
  500. llvm::Value *SrcPtr
  501. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
  502. LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
  503. // Copy the aggregate.
  504. CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
  505. LHS.isVolatileQualified());
  506. return;
  507. }
  508. // Emit the block variables for the array indices, if any.
  509. for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
  510. CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
  511. }
  512. EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
  513. if (!CGF.CGM.getLangOptions().Exceptions)
  514. return;
  515. // FIXME: If we have an array of classes w/ non-trivial destructors,
  516. // we need to destroy in reverse order of construction along the exception
  517. // path.
  518. const RecordType *RT = FieldType->getAs<RecordType>();
  519. if (!RT)
  520. return;
  521. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  522. if (!RD->hasTrivialDestructor())
  523. CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
  524. RD->getDestructor());
  525. }
  526. }
  527. /// Checks whether the given constructor is a valid subject for the
  528. /// complete-to-base constructor delegation optimization, i.e.
  529. /// emitting the complete constructor as a simple call to the base
  530. /// constructor.
  531. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
  532. // Currently we disable the optimization for classes with virtual
  533. // bases because (1) the addresses of parameter variables need to be
  534. // consistent across all initializers but (2) the delegate function
  535. // call necessarily creates a second copy of the parameter variable.
  536. //
  537. // The limiting example (purely theoretical AFAIK):
  538. // struct A { A(int &c) { c++; } };
  539. // struct B : virtual A {
  540. // B(int count) : A(count) { printf("%d\n", count); }
  541. // };
  542. // ...although even this example could in principle be emitted as a
  543. // delegation since the address of the parameter doesn't escape.
  544. if (Ctor->getParent()->getNumVBases()) {
  545. // TODO: white-list trivial vbase initializers. This case wouldn't
  546. // be subject to the restrictions below.
  547. // TODO: white-list cases where:
  548. // - there are no non-reference parameters to the constructor
  549. // - the initializers don't access any non-reference parameters
  550. // - the initializers don't take the address of non-reference
  551. // parameters
  552. // - etc.
  553. // If we ever add any of the above cases, remember that:
  554. // - function-try-blocks will always blacklist this optimization
  555. // - we need to perform the constructor prologue and cleanup in
  556. // EmitConstructorBody.
  557. return false;
  558. }
  559. // We also disable the optimization for variadic functions because
  560. // it's impossible to "re-pass" varargs.
  561. if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
  562. return false;
  563. // FIXME: Decide if we can do a delegation of a delegating constructor.
  564. if (Ctor->isDelegatingConstructor())
  565. return false;
  566. return true;
  567. }
  568. /// EmitConstructorBody - Emits the body of the current constructor.
  569. void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
  570. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
  571. CXXCtorType CtorType = CurGD.getCtorType();
  572. // Before we go any further, try the complete->base constructor
  573. // delegation optimization.
  574. if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
  575. if (CGDebugInfo *DI = getDebugInfo())
  576. DI->EmitLocation(Builder, Ctor->getLocEnd());
  577. EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
  578. return;
  579. }
  580. Stmt *Body = Ctor->getBody();
  581. // Enter the function-try-block before the constructor prologue if
  582. // applicable.
  583. bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
  584. if (IsTryBody)
  585. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  586. EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
  587. // Emit the constructor prologue, i.e. the base and member
  588. // initializers.
  589. EmitCtorPrologue(Ctor, CtorType, Args);
  590. // Emit the body of the statement.
  591. if (IsTryBody)
  592. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  593. else if (Body)
  594. EmitStmt(Body);
  595. // Emit any cleanup blocks associated with the member or base
  596. // initializers, which includes (along the exceptional path) the
  597. // destructors for those members and bases that were fully
  598. // constructed.
  599. PopCleanupBlocks(CleanupDepth);
  600. if (IsTryBody)
  601. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  602. }
  603. /// EmitCtorPrologue - This routine generates necessary code to initialize
  604. /// base classes and non-static data members belonging to this constructor.
  605. void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
  606. CXXCtorType CtorType,
  607. FunctionArgList &Args) {
  608. if (CD->isDelegatingConstructor())
  609. return EmitDelegatingCXXConstructorCall(CD, Args);
  610. const CXXRecordDecl *ClassDecl = CD->getParent();
  611. SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
  612. for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
  613. E = CD->init_end();
  614. B != E; ++B) {
  615. CXXCtorInitializer *Member = (*B);
  616. if (Member->isBaseInitializer()) {
  617. EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
  618. } else {
  619. assert(Member->isAnyMemberInitializer() &&
  620. "Delegating initializer on non-delegating constructor");
  621. MemberInitializers.push_back(Member);
  622. }
  623. }
  624. InitializeVTablePointers(ClassDecl);
  625. for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
  626. EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
  627. }
  628. static bool
  629. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  630. static bool
  631. HasTrivialDestructorBody(ASTContext &Context,
  632. const CXXRecordDecl *BaseClassDecl,
  633. const CXXRecordDecl *MostDerivedClassDecl)
  634. {
  635. // If the destructor is trivial we don't have to check anything else.
  636. if (BaseClassDecl->hasTrivialDestructor())
  637. return true;
  638. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  639. return false;
  640. // Check fields.
  641. for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
  642. E = BaseClassDecl->field_end(); I != E; ++I) {
  643. const FieldDecl *Field = *I;
  644. if (!FieldHasTrivialDestructorBody(Context, Field))
  645. return false;
  646. }
  647. // Check non-virtual bases.
  648. for (CXXRecordDecl::base_class_const_iterator I =
  649. BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
  650. I != E; ++I) {
  651. if (I->isVirtual())
  652. continue;
  653. const CXXRecordDecl *NonVirtualBase =
  654. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  655. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  656. MostDerivedClassDecl))
  657. return false;
  658. }
  659. if (BaseClassDecl == MostDerivedClassDecl) {
  660. // Check virtual bases.
  661. for (CXXRecordDecl::base_class_const_iterator I =
  662. BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
  663. I != E; ++I) {
  664. const CXXRecordDecl *VirtualBase =
  665. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  666. if (!HasTrivialDestructorBody(Context, VirtualBase,
  667. MostDerivedClassDecl))
  668. return false;
  669. }
  670. }
  671. return true;
  672. }
  673. static bool
  674. FieldHasTrivialDestructorBody(ASTContext &Context,
  675. const FieldDecl *Field)
  676. {
  677. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  678. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  679. if (!RT)
  680. return true;
  681. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  682. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  683. }
  684. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  685. /// any vtable pointers before calling this destructor.
  686. static bool CanSkipVTablePointerInitialization(ASTContext &Context,
  687. const CXXDestructorDecl *Dtor) {
  688. if (!Dtor->hasTrivialBody())
  689. return false;
  690. // Check the fields.
  691. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  692. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  693. E = ClassDecl->field_end(); I != E; ++I) {
  694. const FieldDecl *Field = *I;
  695. if (!FieldHasTrivialDestructorBody(Context, Field))
  696. return false;
  697. }
  698. return true;
  699. }
  700. /// EmitDestructorBody - Emits the body of the current destructor.
  701. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  702. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  703. CXXDtorType DtorType = CurGD.getDtorType();
  704. // The call to operator delete in a deleting destructor happens
  705. // outside of the function-try-block, which means it's always
  706. // possible to delegate the destructor body to the complete
  707. // destructor. Do so.
  708. if (DtorType == Dtor_Deleting) {
  709. EnterDtorCleanups(Dtor, Dtor_Deleting);
  710. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  711. LoadCXXThis());
  712. PopCleanupBlock();
  713. return;
  714. }
  715. Stmt *Body = Dtor->getBody();
  716. // If the body is a function-try-block, enter the try before
  717. // anything else.
  718. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  719. if (isTryBody)
  720. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  721. // Enter the epilogue cleanups.
  722. RunCleanupsScope DtorEpilogue(*this);
  723. // If this is the complete variant, just invoke the base variant;
  724. // the epilogue will destruct the virtual bases. But we can't do
  725. // this optimization if the body is a function-try-block, because
  726. // we'd introduce *two* handler blocks.
  727. switch (DtorType) {
  728. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  729. case Dtor_Complete:
  730. // Enter the cleanup scopes for virtual bases.
  731. EnterDtorCleanups(Dtor, Dtor_Complete);
  732. if (!isTryBody) {
  733. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  734. LoadCXXThis());
  735. break;
  736. }
  737. // Fallthrough: act like we're in the base variant.
  738. case Dtor_Base:
  739. // Enter the cleanup scopes for fields and non-virtual bases.
  740. EnterDtorCleanups(Dtor, Dtor_Base);
  741. // Initialize the vtable pointers before entering the body.
  742. if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
  743. InitializeVTablePointers(Dtor->getParent());
  744. if (isTryBody)
  745. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  746. else if (Body)
  747. EmitStmt(Body);
  748. else {
  749. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  750. // nothing to do besides what's in the epilogue
  751. }
  752. // -fapple-kext must inline any call to this dtor into
  753. // the caller's body.
  754. if (getContext().getLangOptions().AppleKext)
  755. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  756. break;
  757. }
  758. // Jump out through the epilogue cleanups.
  759. DtorEpilogue.ForceCleanup();
  760. // Exit the try if applicable.
  761. if (isTryBody)
  762. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  763. }
  764. namespace {
  765. /// Call the operator delete associated with the current destructor.
  766. struct CallDtorDelete : EHScopeStack::Cleanup {
  767. CallDtorDelete() {}
  768. void Emit(CodeGenFunction &CGF, Flags flags) {
  769. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  770. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  771. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  772. CGF.getContext().getTagDeclType(ClassDecl));
  773. }
  774. };
  775. class DestroyField : public EHScopeStack::Cleanup {
  776. const FieldDecl *field;
  777. CodeGenFunction::Destroyer *destroyer;
  778. bool useEHCleanupForArray;
  779. public:
  780. DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
  781. bool useEHCleanupForArray)
  782. : field(field), destroyer(destroyer),
  783. useEHCleanupForArray(useEHCleanupForArray) {}
  784. void Emit(CodeGenFunction &CGF, Flags flags) {
  785. // Find the address of the field.
  786. llvm::Value *thisValue = CGF.LoadCXXThis();
  787. LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
  788. assert(LV.isSimple());
  789. CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
  790. flags.isForNormalCleanup() && useEHCleanupForArray);
  791. }
  792. };
  793. }
  794. /// EmitDtorEpilogue - Emit all code that comes at the end of class's
  795. /// destructor. This is to call destructors on members and base classes
  796. /// in reverse order of their construction.
  797. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  798. CXXDtorType DtorType) {
  799. assert(!DD->isTrivial() &&
  800. "Should not emit dtor epilogue for trivial dtor!");
  801. // The deleting-destructor phase just needs to call the appropriate
  802. // operator delete that Sema picked up.
  803. if (DtorType == Dtor_Deleting) {
  804. assert(DD->getOperatorDelete() &&
  805. "operator delete missing - EmitDtorEpilogue");
  806. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  807. return;
  808. }
  809. const CXXRecordDecl *ClassDecl = DD->getParent();
  810. // Unions have no bases and do not call field destructors.
  811. if (ClassDecl->isUnion())
  812. return;
  813. // The complete-destructor phase just destructs all the virtual bases.
  814. if (DtorType == Dtor_Complete) {
  815. // We push them in the forward order so that they'll be popped in
  816. // the reverse order.
  817. for (CXXRecordDecl::base_class_const_iterator I =
  818. ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
  819. I != E; ++I) {
  820. const CXXBaseSpecifier &Base = *I;
  821. CXXRecordDecl *BaseClassDecl
  822. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  823. // Ignore trivial destructors.
  824. if (BaseClassDecl->hasTrivialDestructor())
  825. continue;
  826. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  827. BaseClassDecl,
  828. /*BaseIsVirtual*/ true);
  829. }
  830. return;
  831. }
  832. assert(DtorType == Dtor_Base);
  833. // Destroy non-virtual bases.
  834. for (CXXRecordDecl::base_class_const_iterator I =
  835. ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
  836. const CXXBaseSpecifier &Base = *I;
  837. // Ignore virtual bases.
  838. if (Base.isVirtual())
  839. continue;
  840. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  841. // Ignore trivial destructors.
  842. if (BaseClassDecl->hasTrivialDestructor())
  843. continue;
  844. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  845. BaseClassDecl,
  846. /*BaseIsVirtual*/ false);
  847. }
  848. // Destroy direct fields.
  849. SmallVector<const FieldDecl *, 16> FieldDecls;
  850. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  851. E = ClassDecl->field_end(); I != E; ++I) {
  852. const FieldDecl *field = *I;
  853. QualType type = field->getType();
  854. QualType::DestructionKind dtorKind = type.isDestructedType();
  855. if (!dtorKind) continue;
  856. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  857. EHStack.pushCleanup<DestroyField>(cleanupKind, field,
  858. getDestroyer(dtorKind),
  859. cleanupKind & EHCleanup);
  860. }
  861. }
  862. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  863. /// constructor for each of several members of an array.
  864. ///
  865. /// \param ctor the constructor to call for each element
  866. /// \param argBegin,argEnd the arguments to evaluate and pass to the
  867. /// constructor
  868. /// \param arrayType the type of the array to initialize
  869. /// \param arrayBegin an arrayType*
  870. /// \param zeroInitialize true if each element should be
  871. /// zero-initialized before it is constructed
  872. void
  873. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  874. const ConstantArrayType *arrayType,
  875. llvm::Value *arrayBegin,
  876. CallExpr::const_arg_iterator argBegin,
  877. CallExpr::const_arg_iterator argEnd,
  878. bool zeroInitialize) {
  879. QualType elementType;
  880. llvm::Value *numElements =
  881. emitArrayLength(arrayType, elementType, arrayBegin);
  882. EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
  883. argBegin, argEnd, zeroInitialize);
  884. }
  885. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  886. /// constructor for each of several members of an array.
  887. ///
  888. /// \param ctor the constructor to call for each element
  889. /// \param numElements the number of elements in the array;
  890. /// may be zero
  891. /// \param argBegin,argEnd the arguments to evaluate and pass to the
  892. /// constructor
  893. /// \param arrayBegin a T*, where T is the type constructed by ctor
  894. /// \param zeroInitialize true if each element should be
  895. /// zero-initialized before it is constructed
  896. void
  897. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  898. llvm::Value *numElements,
  899. llvm::Value *arrayBegin,
  900. CallExpr::const_arg_iterator argBegin,
  901. CallExpr::const_arg_iterator argEnd,
  902. bool zeroInitialize) {
  903. // It's legal for numElements to be zero. This can happen both
  904. // dynamically, because x can be zero in 'new A[x]', and statically,
  905. // because of GCC extensions that permit zero-length arrays. There
  906. // are probably legitimate places where we could assume that this
  907. // doesn't happen, but it's not clear that it's worth it.
  908. llvm::BranchInst *zeroCheckBranch = 0;
  909. // Optimize for a constant count.
  910. llvm::ConstantInt *constantCount
  911. = dyn_cast<llvm::ConstantInt>(numElements);
  912. if (constantCount) {
  913. // Just skip out if the constant count is zero.
  914. if (constantCount->isZero()) return;
  915. // Otherwise, emit the check.
  916. } else {
  917. llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
  918. llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
  919. zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
  920. EmitBlock(loopBB);
  921. }
  922. // Find the end of the array.
  923. llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
  924. "arrayctor.end");
  925. // Enter the loop, setting up a phi for the current location to initialize.
  926. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  927. llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
  928. EmitBlock(loopBB);
  929. llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
  930. "arrayctor.cur");
  931. cur->addIncoming(arrayBegin, entryBB);
  932. // Inside the loop body, emit the constructor call on the array element.
  933. QualType type = getContext().getTypeDeclType(ctor->getParent());
  934. // Zero initialize the storage, if requested.
  935. if (zeroInitialize)
  936. EmitNullInitialization(cur, type);
  937. // C++ [class.temporary]p4:
  938. // There are two contexts in which temporaries are destroyed at a different
  939. // point than the end of the full-expression. The first context is when a
  940. // default constructor is called to initialize an element of an array.
  941. // If the constructor has one or more default arguments, the destruction of
  942. // every temporary created in a default argument expression is sequenced
  943. // before the construction of the next array element, if any.
  944. {
  945. RunCleanupsScope Scope(*this);
  946. // Evaluate the constructor and its arguments in a regular
  947. // partial-destroy cleanup.
  948. if (getLangOptions().Exceptions &&
  949. !ctor->getParent()->hasTrivialDestructor()) {
  950. Destroyer *destroyer = destroyCXXObject;
  951. pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
  952. }
  953. EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
  954. cur, argBegin, argEnd);
  955. }
  956. // Go to the next element.
  957. llvm::Value *next =
  958. Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
  959. "arrayctor.next");
  960. cur->addIncoming(next, Builder.GetInsertBlock());
  961. // Check whether that's the end of the loop.
  962. llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
  963. llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
  964. Builder.CreateCondBr(done, contBB, loopBB);
  965. // Patch the earlier check to skip over the loop.
  966. if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
  967. EmitBlock(contBB);
  968. }
  969. void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
  970. llvm::Value *addr,
  971. QualType type) {
  972. const RecordType *rtype = type->castAs<RecordType>();
  973. const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
  974. const CXXDestructorDecl *dtor = record->getDestructor();
  975. assert(!dtor->isTrivial());
  976. CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
  977. addr);
  978. }
  979. void
  980. CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  981. CXXCtorType Type, bool ForVirtualBase,
  982. llvm::Value *This,
  983. CallExpr::const_arg_iterator ArgBeg,
  984. CallExpr::const_arg_iterator ArgEnd) {
  985. CGDebugInfo *DI = getDebugInfo();
  986. if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
  987. // If debug info for this class has been emitted then this is the right time
  988. // to do so.
  989. const CXXRecordDecl *Parent = D->getParent();
  990. DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
  991. Parent->getLocation());
  992. }
  993. if (D->isTrivial()) {
  994. if (ArgBeg == ArgEnd) {
  995. // Trivial default constructor, no codegen required.
  996. assert(D->isDefaultConstructor() &&
  997. "trivial 0-arg ctor not a default ctor");
  998. return;
  999. }
  1000. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  1001. assert(D->isCopyOrMoveConstructor() &&
  1002. "trivial 1-arg ctor not a copy/move ctor");
  1003. const Expr *E = (*ArgBeg);
  1004. QualType Ty = E->getType();
  1005. llvm::Value *Src = EmitLValue(E).getAddress();
  1006. EmitAggregateCopy(This, Src, Ty);
  1007. return;
  1008. }
  1009. llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
  1010. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
  1011. EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
  1012. }
  1013. void
  1014. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1015. llvm::Value *This, llvm::Value *Src,
  1016. CallExpr::const_arg_iterator ArgBeg,
  1017. CallExpr::const_arg_iterator ArgEnd) {
  1018. if (D->isTrivial()) {
  1019. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  1020. assert(D->isCopyOrMoveConstructor() &&
  1021. "trivial 1-arg ctor not a copy/move ctor");
  1022. EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
  1023. return;
  1024. }
  1025. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
  1026. clang::Ctor_Complete);
  1027. assert(D->isInstance() &&
  1028. "Trying to emit a member call expr on a static method!");
  1029. const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
  1030. CallArgList Args;
  1031. // Push the this ptr.
  1032. Args.add(RValue::get(This), D->getThisType(getContext()));
  1033. // Push the src ptr.
  1034. QualType QT = *(FPT->arg_type_begin());
  1035. llvm::Type *t = CGM.getTypes().ConvertType(QT);
  1036. Src = Builder.CreateBitCast(Src, t);
  1037. Args.add(RValue::get(Src), QT);
  1038. // Skip over first argument (Src).
  1039. ++ArgBeg;
  1040. CallExpr::const_arg_iterator Arg = ArgBeg;
  1041. for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
  1042. E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
  1043. assert(Arg != ArgEnd && "Running over edge of argument list!");
  1044. EmitCallArg(Args, *Arg, *I);
  1045. }
  1046. // Either we've emitted all the call args, or we have a call to a
  1047. // variadic function.
  1048. assert((Arg == ArgEnd || FPT->isVariadic()) &&
  1049. "Extra arguments in non-variadic function!");
  1050. // If we still have any arguments, emit them using the type of the argument.
  1051. for (; Arg != ArgEnd; ++Arg) {
  1052. QualType ArgType = Arg->getType();
  1053. EmitCallArg(Args, *Arg, ArgType);
  1054. }
  1055. EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
  1056. ReturnValueSlot(), Args, D);
  1057. }
  1058. void
  1059. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1060. CXXCtorType CtorType,
  1061. const FunctionArgList &Args) {
  1062. CallArgList DelegateArgs;
  1063. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  1064. assert(I != E && "no parameters to constructor");
  1065. // this
  1066. DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
  1067. ++I;
  1068. // vtt
  1069. if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
  1070. /*ForVirtualBase=*/false)) {
  1071. QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
  1072. DelegateArgs.add(RValue::get(VTT), VoidPP);
  1073. if (CodeGenVTables::needsVTTParameter(CurGD)) {
  1074. assert(I != E && "cannot skip vtt parameter, already done with args");
  1075. assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
  1076. ++I;
  1077. }
  1078. }
  1079. // Explicit arguments.
  1080. for (; I != E; ++I) {
  1081. const VarDecl *param = *I;
  1082. EmitDelegateCallArg(DelegateArgs, param);
  1083. }
  1084. EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
  1085. CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
  1086. ReturnValueSlot(), DelegateArgs, Ctor);
  1087. }
  1088. namespace {
  1089. struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
  1090. const CXXDestructorDecl *Dtor;
  1091. llvm::Value *Addr;
  1092. CXXDtorType Type;
  1093. CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
  1094. CXXDtorType Type)
  1095. : Dtor(D), Addr(Addr), Type(Type) {}
  1096. void Emit(CodeGenFunction &CGF, Flags flags) {
  1097. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  1098. Addr);
  1099. }
  1100. };
  1101. }
  1102. void
  1103. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1104. const FunctionArgList &Args) {
  1105. assert(Ctor->isDelegatingConstructor());
  1106. llvm::Value *ThisPtr = LoadCXXThis();
  1107. QualType Ty = getContext().getTagDeclType(Ctor->getParent());
  1108. CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
  1109. AggValueSlot AggSlot =
  1110. AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
  1111. AggValueSlot::IsDestructed,
  1112. AggValueSlot::DoesNotNeedGCBarriers,
  1113. AggValueSlot::IsNotAliased);
  1114. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  1115. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  1116. if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  1117. CXXDtorType Type =
  1118. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  1119. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  1120. ClassDecl->getDestructor(),
  1121. ThisPtr, Type);
  1122. }
  1123. }
  1124. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  1125. CXXDtorType Type,
  1126. bool ForVirtualBase,
  1127. llvm::Value *This) {
  1128. llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
  1129. ForVirtualBase);
  1130. llvm::Value *Callee = 0;
  1131. if (getContext().getLangOptions().AppleKext)
  1132. Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
  1133. DD->getParent());
  1134. if (!Callee)
  1135. Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
  1136. EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
  1137. }
  1138. namespace {
  1139. struct CallLocalDtor : EHScopeStack::Cleanup {
  1140. const CXXDestructorDecl *Dtor;
  1141. llvm::Value *Addr;
  1142. CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
  1143. : Dtor(D), Addr(Addr) {}
  1144. void Emit(CodeGenFunction &CGF, Flags flags) {
  1145. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  1146. /*ForVirtualBase=*/false, Addr);
  1147. }
  1148. };
  1149. }
  1150. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  1151. llvm::Value *Addr) {
  1152. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
  1153. }
  1154. void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
  1155. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  1156. if (!ClassDecl) return;
  1157. if (ClassDecl->hasTrivialDestructor()) return;
  1158. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  1159. assert(D && D->isUsed() && "destructor not marked as used!");
  1160. PushDestructorCleanup(D, Addr);
  1161. }
  1162. llvm::Value *
  1163. CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
  1164. const CXXRecordDecl *ClassDecl,
  1165. const CXXRecordDecl *BaseClassDecl) {
  1166. llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
  1167. CharUnits VBaseOffsetOffset =
  1168. CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
  1169. llvm::Value *VBaseOffsetPtr =
  1170. Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
  1171. "vbase.offset.ptr");
  1172. llvm::Type *PtrDiffTy =
  1173. ConvertType(getContext().getPointerDiffType());
  1174. VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
  1175. PtrDiffTy->getPointerTo());
  1176. llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
  1177. return VBaseOffset;
  1178. }
  1179. void
  1180. CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
  1181. const CXXRecordDecl *NearestVBase,
  1182. CharUnits OffsetFromNearestVBase,
  1183. llvm::Constant *VTable,
  1184. const CXXRecordDecl *VTableClass) {
  1185. const CXXRecordDecl *RD = Base.getBase();
  1186. // Compute the address point.
  1187. llvm::Value *VTableAddressPoint;
  1188. // Check if we need to use a vtable from the VTT.
  1189. if (CodeGenVTables::needsVTTParameter(CurGD) &&
  1190. (RD->getNumVBases() || NearestVBase)) {
  1191. // Get the secondary vpointer index.
  1192. uint64_t VirtualPointerIndex =
  1193. CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
  1194. /// Load the VTT.
  1195. llvm::Value *VTT = LoadCXXVTT();
  1196. if (VirtualPointerIndex)
  1197. VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
  1198. // And load the address point from the VTT.
  1199. VTableAddressPoint = Builder.CreateLoad(VTT);
  1200. } else {
  1201. uint64_t AddressPoint =
  1202. CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
  1203. VTableAddressPoint =
  1204. Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
  1205. }
  1206. // Compute where to store the address point.
  1207. llvm::Value *VirtualOffset = 0;
  1208. CharUnits NonVirtualOffset = CharUnits::Zero();
  1209. if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
  1210. // We need to use the virtual base offset offset because the virtual base
  1211. // might have a different offset in the most derived class.
  1212. VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
  1213. NearestVBase);
  1214. NonVirtualOffset = OffsetFromNearestVBase;
  1215. } else {
  1216. // We can just use the base offset in the complete class.
  1217. NonVirtualOffset = Base.getBaseOffset();
  1218. }
  1219. // Apply the offsets.
  1220. llvm::Value *VTableField = LoadCXXThis();
  1221. if (!NonVirtualOffset.isZero() || VirtualOffset)
  1222. VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
  1223. NonVirtualOffset,
  1224. VirtualOffset);
  1225. // Finally, store the address point.
  1226. llvm::Type *AddressPointPtrTy =
  1227. VTableAddressPoint->getType()->getPointerTo();
  1228. VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
  1229. Builder.CreateStore(VTableAddressPoint, VTableField);
  1230. }
  1231. void
  1232. CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
  1233. const CXXRecordDecl *NearestVBase,
  1234. CharUnits OffsetFromNearestVBase,
  1235. bool BaseIsNonVirtualPrimaryBase,
  1236. llvm::Constant *VTable,
  1237. const CXXRecordDecl *VTableClass,
  1238. VisitedVirtualBasesSetTy& VBases) {
  1239. // If this base is a non-virtual primary base the address point has already
  1240. // been set.
  1241. if (!BaseIsNonVirtualPrimaryBase) {
  1242. // Initialize the vtable pointer for this base.
  1243. InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
  1244. VTable, VTableClass);
  1245. }
  1246. const CXXRecordDecl *RD = Base.getBase();
  1247. // Traverse bases.
  1248. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1249. E = RD->bases_end(); I != E; ++I) {
  1250. CXXRecordDecl *BaseDecl
  1251. = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1252. // Ignore classes without a vtable.
  1253. if (!BaseDecl->isDynamicClass())
  1254. continue;
  1255. CharUnits BaseOffset;
  1256. CharUnits BaseOffsetFromNearestVBase;
  1257. bool BaseDeclIsNonVirtualPrimaryBase;
  1258. if (I->isVirtual()) {
  1259. // Check if we've visited this virtual base before.
  1260. if (!VBases.insert(BaseDecl))
  1261. continue;
  1262. const ASTRecordLayout &Layout =
  1263. getContext().getASTRecordLayout(VTableClass);
  1264. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  1265. BaseOffsetFromNearestVBase = CharUnits::Zero();
  1266. BaseDeclIsNonVirtualPrimaryBase = false;
  1267. } else {
  1268. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1269. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  1270. BaseOffsetFromNearestVBase =
  1271. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  1272. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  1273. }
  1274. InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
  1275. I->isVirtual() ? BaseDecl : NearestVBase,
  1276. BaseOffsetFromNearestVBase,
  1277. BaseDeclIsNonVirtualPrimaryBase,
  1278. VTable, VTableClass, VBases);
  1279. }
  1280. }
  1281. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  1282. // Ignore classes without a vtable.
  1283. if (!RD->isDynamicClass())
  1284. return;
  1285. // Get the VTable.
  1286. llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
  1287. // Initialize the vtable pointers for this class and all of its bases.
  1288. VisitedVirtualBasesSetTy VBases;
  1289. InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
  1290. /*NearestVBase=*/0,
  1291. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  1292. /*BaseIsNonVirtualPrimaryBase=*/false,
  1293. VTable, RD, VBases);
  1294. }
  1295. llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
  1296. llvm::Type *Ty) {
  1297. llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
  1298. return Builder.CreateLoad(VTablePtrSrc, "vtable");
  1299. }
  1300. static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
  1301. const Expr *E = Base;
  1302. while (true) {
  1303. E = E->IgnoreParens();
  1304. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1305. if (CE->getCastKind() == CK_DerivedToBase ||
  1306. CE->getCastKind() == CK_UncheckedDerivedToBase ||
  1307. CE->getCastKind() == CK_NoOp) {
  1308. E = CE->getSubExpr();
  1309. continue;
  1310. }
  1311. }
  1312. break;
  1313. }
  1314. QualType DerivedType = E->getType();
  1315. if (const PointerType *PTy = DerivedType->getAs<PointerType>())
  1316. DerivedType = PTy->getPointeeType();
  1317. return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
  1318. }
  1319. // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
  1320. // quite what we want.
  1321. static const Expr *skipNoOpCastsAndParens(const Expr *E) {
  1322. while (true) {
  1323. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  1324. E = PE->getSubExpr();
  1325. continue;
  1326. }
  1327. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1328. if (CE->getCastKind() == CK_NoOp) {
  1329. E = CE->getSubExpr();
  1330. continue;
  1331. }
  1332. }
  1333. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  1334. if (UO->getOpcode() == UO_Extension) {
  1335. E = UO->getSubExpr();
  1336. continue;
  1337. }
  1338. }
  1339. return E;
  1340. }
  1341. }
  1342. /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
  1343. /// function call on the given expr can be devirtualized.
  1344. static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
  1345. const CXXMethodDecl *MD) {
  1346. // If the most derived class is marked final, we know that no subclass can
  1347. // override this member function and so we can devirtualize it. For example:
  1348. //
  1349. // struct A { virtual void f(); }
  1350. // struct B final : A { };
  1351. //
  1352. // void f(B *b) {
  1353. // b->f();
  1354. // }
  1355. //
  1356. const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
  1357. if (MostDerivedClassDecl->hasAttr<FinalAttr>())
  1358. return true;
  1359. // If the member function is marked 'final', we know that it can't be
  1360. // overridden and can therefore devirtualize it.
  1361. if (MD->hasAttr<FinalAttr>())
  1362. return true;
  1363. // Similarly, if the class itself is marked 'final' it can't be overridden
  1364. // and we can therefore devirtualize the member function call.
  1365. if (MD->getParent()->hasAttr<FinalAttr>())
  1366. return true;
  1367. Base = skipNoOpCastsAndParens(Base);
  1368. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  1369. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  1370. // This is a record decl. We know the type and can devirtualize it.
  1371. return VD->getType()->isRecordType();
  1372. }
  1373. return false;
  1374. }
  1375. // We can always devirtualize calls on temporary object expressions.
  1376. if (isa<CXXConstructExpr>(Base))
  1377. return true;
  1378. // And calls on bound temporaries.
  1379. if (isa<CXXBindTemporaryExpr>(Base))
  1380. return true;
  1381. // Check if this is a call expr that returns a record type.
  1382. if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
  1383. return CE->getCallReturnType()->isRecordType();
  1384. // We can't devirtualize the call.
  1385. return false;
  1386. }
  1387. static bool UseVirtualCall(ASTContext &Context,
  1388. const CXXOperatorCallExpr *CE,
  1389. const CXXMethodDecl *MD) {
  1390. if (!MD->isVirtual())
  1391. return false;
  1392. // When building with -fapple-kext, all calls must go through the vtable since
  1393. // the kernel linker can do runtime patching of vtables.
  1394. if (Context.getLangOptions().AppleKext)
  1395. return true;
  1396. return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
  1397. }
  1398. llvm::Value *
  1399. CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
  1400. const CXXMethodDecl *MD,
  1401. llvm::Value *This) {
  1402. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  1403. llvm::Type *Ty =
  1404. CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
  1405. FPT->isVariadic());
  1406. if (UseVirtualCall(getContext(), E, MD))
  1407. return BuildVirtualCall(MD, This, Ty);
  1408. return CGM.GetAddrOfFunction(MD, Ty);
  1409. }