CGClass.cpp 106 KB

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