CGDecl.cpp 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686
  1. //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit Decl nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGBlocks.h"
  13. #include "CGCXXABI.h"
  14. #include "CGCleanup.h"
  15. #include "CGDebugInfo.h"
  16. #include "CGOpenCLRuntime.h"
  17. #include "CGOpenMPRuntime.h"
  18. #include "CodeGenFunction.h"
  19. #include "CodeGenModule.h"
  20. #include "ConstantEmitter.h"
  21. #include "PatternInit.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/Attr.h"
  25. #include "clang/AST/CharUnits.h"
  26. #include "clang/AST/Decl.h"
  27. #include "clang/AST/DeclObjC.h"
  28. #include "clang/AST/DeclOpenMP.h"
  29. #include "clang/Basic/CodeGenOptions.h"
  30. #include "clang/Basic/SourceManager.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "clang/CodeGen/CGFunctionInfo.h"
  33. #include "clang/Sema/Sema.h"
  34. #include "llvm/Analysis/ValueTracking.h"
  35. #include "llvm/IR/DataLayout.h"
  36. #include "llvm/IR/GlobalVariable.h"
  37. #include "llvm/IR/Intrinsics.h"
  38. #include "llvm/IR/Type.h"
  39. using namespace clang;
  40. using namespace CodeGen;
  41. static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
  42. "Clang max alignment greater than what LLVM supports?");
  43. void CodeGenFunction::EmitDecl(const Decl &D) {
  44. switch (D.getKind()) {
  45. case Decl::BuiltinTemplate:
  46. case Decl::TranslationUnit:
  47. case Decl::ExternCContext:
  48. case Decl::Namespace:
  49. case Decl::UnresolvedUsingTypename:
  50. case Decl::ClassTemplateSpecialization:
  51. case Decl::ClassTemplatePartialSpecialization:
  52. case Decl::VarTemplateSpecialization:
  53. case Decl::VarTemplatePartialSpecialization:
  54. case Decl::TemplateTypeParm:
  55. case Decl::UnresolvedUsingValue:
  56. case Decl::NonTypeTemplateParm:
  57. case Decl::CXXDeductionGuide:
  58. case Decl::CXXMethod:
  59. case Decl::CXXConstructor:
  60. case Decl::CXXDestructor:
  61. case Decl::CXXConversion:
  62. case Decl::Field:
  63. case Decl::MSProperty:
  64. case Decl::IndirectField:
  65. case Decl::ObjCIvar:
  66. case Decl::ObjCAtDefsField:
  67. case Decl::ParmVar:
  68. case Decl::ImplicitParam:
  69. case Decl::ClassTemplate:
  70. case Decl::VarTemplate:
  71. case Decl::FunctionTemplate:
  72. case Decl::TypeAliasTemplate:
  73. case Decl::TemplateTemplateParm:
  74. case Decl::ObjCMethod:
  75. case Decl::ObjCCategory:
  76. case Decl::ObjCProtocol:
  77. case Decl::ObjCInterface:
  78. case Decl::ObjCCategoryImpl:
  79. case Decl::ObjCImplementation:
  80. case Decl::ObjCProperty:
  81. case Decl::ObjCCompatibleAlias:
  82. case Decl::PragmaComment:
  83. case Decl::PragmaDetectMismatch:
  84. case Decl::AccessSpec:
  85. case Decl::LinkageSpec:
  86. case Decl::Export:
  87. case Decl::ObjCPropertyImpl:
  88. case Decl::FileScopeAsm:
  89. case Decl::Friend:
  90. case Decl::FriendTemplate:
  91. case Decl::Block:
  92. case Decl::Captured:
  93. case Decl::ClassScopeFunctionSpecialization:
  94. case Decl::UsingShadow:
  95. case Decl::ConstructorUsingShadow:
  96. case Decl::ObjCTypeParam:
  97. case Decl::Binding:
  98. case Decl::UnresolvedUsingIfExists:
  99. llvm_unreachable("Declaration should not be in declstmts!");
  100. case Decl::Record: // struct/union/class X;
  101. case Decl::CXXRecord: // struct/union/class X; [C++]
  102. if (CGDebugInfo *DI = getDebugInfo())
  103. if (cast<RecordDecl>(D).getDefinition())
  104. DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
  105. return;
  106. case Decl::Enum: // enum X;
  107. if (CGDebugInfo *DI = getDebugInfo())
  108. if (cast<EnumDecl>(D).getDefinition())
  109. DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
  110. return;
  111. case Decl::Function: // void X();
  112. case Decl::EnumConstant: // enum ? { X = ? }
  113. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  114. case Decl::Label: // __label__ x;
  115. case Decl::Import:
  116. case Decl::MSGuid: // __declspec(uuid("..."))
  117. case Decl::TemplateParamObject:
  118. case Decl::OMPThreadPrivate:
  119. case Decl::OMPAllocate:
  120. case Decl::OMPCapturedExpr:
  121. case Decl::OMPRequires:
  122. case Decl::Empty:
  123. case Decl::Concept:
  124. case Decl::LifetimeExtendedTemporary:
  125. case Decl::RequiresExprBody:
  126. // None of these decls require codegen support.
  127. return;
  128. case Decl::NamespaceAlias:
  129. if (CGDebugInfo *DI = getDebugInfo())
  130. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
  131. return;
  132. case Decl::Using: // using X; [C++]
  133. if (CGDebugInfo *DI = getDebugInfo())
  134. DI->EmitUsingDecl(cast<UsingDecl>(D));
  135. return;
  136. case Decl::UsingEnum: // using enum X; [C++]
  137. if (CGDebugInfo *DI = getDebugInfo())
  138. DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
  139. return;
  140. case Decl::UsingPack:
  141. for (auto *Using : cast<UsingPackDecl>(D).expansions())
  142. EmitDecl(*Using);
  143. return;
  144. case Decl::UsingDirective: // using namespace X; [C++]
  145. if (CGDebugInfo *DI = getDebugInfo())
  146. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
  147. return;
  148. case Decl::Var:
  149. case Decl::Decomposition: {
  150. const VarDecl &VD = cast<VarDecl>(D);
  151. assert(VD.isLocalVarDecl() &&
  152. "Should not see file-scope variables inside a function!");
  153. EmitVarDecl(VD);
  154. if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
  155. for (auto *B : DD->bindings())
  156. if (auto *HD = B->getHoldingVar())
  157. EmitVarDecl(*HD);
  158. return;
  159. }
  160. case Decl::OMPDeclareReduction:
  161. return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
  162. case Decl::OMPDeclareMapper:
  163. return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
  164. case Decl::Typedef: // typedef int X;
  165. case Decl::TypeAlias: { // using X = int; [C++0x]
  166. QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
  167. if (CGDebugInfo *DI = getDebugInfo())
  168. DI->EmitAndRetainType(Ty);
  169. if (Ty->isVariablyModifiedType())
  170. EmitVariablyModifiedType(Ty);
  171. return;
  172. }
  173. }
  174. }
  175. /// EmitVarDecl - This method handles emission of any variable declaration
  176. /// inside a function, including static vars etc.
  177. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  178. if (D.hasExternalStorage())
  179. // Don't emit it now, allow it to be emitted lazily on its first use.
  180. return;
  181. // Some function-scope variable does not have static storage but still
  182. // needs to be emitted like a static variable, e.g. a function-scope
  183. // variable in constant address space in OpenCL.
  184. if (D.getStorageDuration() != SD_Automatic) {
  185. // Static sampler variables translated to function calls.
  186. if (D.getType()->isSamplerT())
  187. return;
  188. llvm::GlobalValue::LinkageTypes Linkage =
  189. CGM.getLLVMLinkageVarDefinition(&D, /*IsConstant=*/false);
  190. // FIXME: We need to force the emission/use of a guard variable for
  191. // some variables even if we can constant-evaluate them because
  192. // we can't guarantee every translation unit will constant-evaluate them.
  193. return EmitStaticVarDecl(D, Linkage);
  194. }
  195. if (D.getType().getAddressSpace() == LangAS::opencl_local)
  196. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  197. assert(D.hasLocalStorage());
  198. return EmitAutoVarDecl(D);
  199. }
  200. static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
  201. if (CGM.getLangOpts().CPlusPlus)
  202. return CGM.getMangledName(&D).str();
  203. // If this isn't C++, we don't need a mangled name, just a pretty one.
  204. assert(!D.isExternallyVisible() && "name shouldn't matter");
  205. std::string ContextName;
  206. const DeclContext *DC = D.getDeclContext();
  207. if (auto *CD = dyn_cast<CapturedDecl>(DC))
  208. DC = cast<DeclContext>(CD->getNonClosureContext());
  209. if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  210. ContextName = std::string(CGM.getMangledName(FD));
  211. else if (const auto *BD = dyn_cast<BlockDecl>(DC))
  212. ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
  213. else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
  214. ContextName = OMD->getSelector().getAsString();
  215. else
  216. llvm_unreachable("Unknown context for static var decl");
  217. ContextName += "." + D.getNameAsString();
  218. return ContextName;
  219. }
  220. llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
  221. const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
  222. // In general, we don't always emit static var decls once before we reference
  223. // them. It is possible to reference them before emitting the function that
  224. // contains them, and it is possible to emit the containing function multiple
  225. // times.
  226. if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
  227. return ExistingGV;
  228. QualType Ty = D.getType();
  229. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  230. // Use the label if the variable is renamed with the asm-label extension.
  231. std::string Name;
  232. if (D.hasAttr<AsmLabelAttr>())
  233. Name = std::string(getMangledName(&D));
  234. else
  235. Name = getStaticDeclName(*this, D);
  236. llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
  237. LangAS AS = GetGlobalVarAddressSpace(&D);
  238. unsigned TargetAS = getContext().getTargetAddressSpace(AS);
  239. // OpenCL variables in local address space and CUDA shared
  240. // variables cannot have an initializer.
  241. llvm::Constant *Init = nullptr;
  242. if (Ty.getAddressSpace() == LangAS::opencl_local ||
  243. D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
  244. Init = llvm::UndefValue::get(LTy);
  245. else
  246. Init = EmitNullConstant(Ty);
  247. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  248. getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
  249. nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  250. GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
  251. if (supportsCOMDAT() && GV->isWeakForLinker())
  252. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  253. if (D.getTLSKind())
  254. setTLSMode(GV, D);
  255. setGVProperties(GV, &D);
  256. // Make sure the result is of the correct type.
  257. LangAS ExpectedAS = Ty.getAddressSpace();
  258. llvm::Constant *Addr = GV;
  259. if (AS != ExpectedAS) {
  260. Addr = getTargetCodeGenInfo().performAddrSpaceCast(
  261. *this, GV, AS, ExpectedAS,
  262. LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
  263. }
  264. setStaticLocalDeclAddress(&D, Addr);
  265. // Ensure that the static local gets initialized by making sure the parent
  266. // function gets emitted eventually.
  267. const Decl *DC = cast<Decl>(D.getDeclContext());
  268. // We can't name blocks or captured statements directly, so try to emit their
  269. // parents.
  270. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
  271. DC = DC->getNonClosureContext();
  272. // FIXME: Ensure that global blocks get emitted.
  273. if (!DC)
  274. return Addr;
  275. }
  276. GlobalDecl GD;
  277. if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
  278. GD = GlobalDecl(CD, Ctor_Base);
  279. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
  280. GD = GlobalDecl(DD, Dtor_Base);
  281. else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  282. GD = GlobalDecl(FD);
  283. else {
  284. // Don't do anything for Obj-C method decls or global closures. We should
  285. // never defer them.
  286. assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
  287. }
  288. if (GD.getDecl()) {
  289. // Disable emission of the parent function for the OpenMP device codegen.
  290. CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
  291. (void)GetAddrOfGlobal(GD);
  292. }
  293. return Addr;
  294. }
  295. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  296. /// global variable that has already been created for it. If the initializer
  297. /// has a different type than GV does, this may free GV and return a different
  298. /// one. Otherwise it just returns GV.
  299. llvm::GlobalVariable *
  300. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  301. llvm::GlobalVariable *GV) {
  302. ConstantEmitter emitter(*this);
  303. llvm::Constant *Init = emitter.tryEmitForInitializer(D);
  304. // If constant emission failed, then this should be a C++ static
  305. // initializer.
  306. if (!Init) {
  307. if (!getLangOpts().CPlusPlus)
  308. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  309. else if (HaveInsertPoint()) {
  310. // Since we have a static initializer, this global variable can't
  311. // be constant.
  312. GV->setConstant(false);
  313. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  314. }
  315. return GV;
  316. }
  317. // The initializer may differ in type from the global. Rewrite
  318. // the global to match the initializer. (We have to do this
  319. // because some types, like unions, can't be completely represented
  320. // in the LLVM type system.)
  321. if (GV->getValueType() != Init->getType()) {
  322. llvm::GlobalVariable *OldGV = GV;
  323. GV = new llvm::GlobalVariable(
  324. CGM.getModule(), Init->getType(), OldGV->isConstant(),
  325. OldGV->getLinkage(), Init, "",
  326. /*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
  327. OldGV->getType()->getPointerAddressSpace());
  328. GV->setVisibility(OldGV->getVisibility());
  329. GV->setDSOLocal(OldGV->isDSOLocal());
  330. GV->setComdat(OldGV->getComdat());
  331. // Steal the name of the old global
  332. GV->takeName(OldGV);
  333. // Replace all uses of the old global with the new global
  334. llvm::Constant *NewPtrForOldDecl =
  335. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  336. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  337. // Erase the old global, since it is no longer used.
  338. OldGV->eraseFromParent();
  339. }
  340. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  341. GV->setInitializer(Init);
  342. emitter.finalize(GV);
  343. if (D.needsDestruction(getContext()) == QualType::DK_cxx_destructor &&
  344. HaveInsertPoint()) {
  345. // We have a constant initializer, but a nontrivial destructor. We still
  346. // need to perform a guarded "initialization" in order to register the
  347. // destructor.
  348. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  349. }
  350. return GV;
  351. }
  352. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  353. llvm::GlobalValue::LinkageTypes Linkage) {
  354. // Check to see if we already have a global variable for this
  355. // declaration. This can happen when double-emitting function
  356. // bodies, e.g. with complete and base constructors.
  357. llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
  358. CharUnits alignment = getContext().getDeclAlign(&D);
  359. // Store into LocalDeclMap before generating initializer to handle
  360. // circular references.
  361. llvm::Type *elemTy = ConvertTypeForMem(D.getType());
  362. setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
  363. // We can't have a VLA here, but we can have a pointer to a VLA,
  364. // even though that doesn't really make any sense.
  365. // Make sure to evaluate VLA bounds now so that we have them for later.
  366. if (D.getType()->isVariablyModifiedType())
  367. EmitVariablyModifiedType(D.getType());
  368. // Save the type in case adding the initializer forces a type change.
  369. llvm::Type *expectedType = addr->getType();
  370. llvm::GlobalVariable *var =
  371. cast<llvm::GlobalVariable>(addr->stripPointerCasts());
  372. // CUDA's local and local static __shared__ variables should not
  373. // have any non-empty initializers. This is ensured by Sema.
  374. // Whatever initializer such variable may have when it gets here is
  375. // a no-op and should not be emitted.
  376. bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  377. D.hasAttr<CUDASharedAttr>();
  378. // If this value has an initializer, emit it.
  379. if (D.getInit() && !isCudaSharedVar)
  380. var = AddInitializerToStaticVarDecl(D, var);
  381. var->setAlignment(alignment.getAsAlign());
  382. if (D.hasAttr<AnnotateAttr>())
  383. CGM.AddGlobalAnnotations(&D, var);
  384. if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
  385. var->addAttribute("bss-section", SA->getName());
  386. if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
  387. var->addAttribute("data-section", SA->getName());
  388. if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
  389. var->addAttribute("rodata-section", SA->getName());
  390. if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
  391. var->addAttribute("relro-section", SA->getName());
  392. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  393. var->setSection(SA->getName());
  394. if (D.hasAttr<RetainAttr>())
  395. CGM.addUsedGlobal(var);
  396. else if (D.hasAttr<UsedAttr>())
  397. CGM.addUsedOrCompilerUsedGlobal(var);
  398. // We may have to cast the constant because of the initializer
  399. // mismatch above.
  400. //
  401. // FIXME: It is really dangerous to store this in the map; if anyone
  402. // RAUW's the GV uses of this constant will be invalid.
  403. llvm::Constant *castedAddr =
  404. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
  405. LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
  406. CGM.setStaticLocalDeclAddress(&D, castedAddr);
  407. CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
  408. // Emit global variable debug descriptor for static vars.
  409. CGDebugInfo *DI = getDebugInfo();
  410. if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
  411. DI->setLocation(D.getLocation());
  412. DI->EmitGlobalVariable(var, &D);
  413. }
  414. }
  415. namespace {
  416. struct DestroyObject final : EHScopeStack::Cleanup {
  417. DestroyObject(Address addr, QualType type,
  418. CodeGenFunction::Destroyer *destroyer,
  419. bool useEHCleanupForArray)
  420. : addr(addr), type(type), destroyer(destroyer),
  421. useEHCleanupForArray(useEHCleanupForArray) {}
  422. Address addr;
  423. QualType type;
  424. CodeGenFunction::Destroyer *destroyer;
  425. bool useEHCleanupForArray;
  426. void Emit(CodeGenFunction &CGF, Flags flags) override {
  427. // Don't use an EH cleanup recursively from an EH cleanup.
  428. bool useEHCleanupForArray =
  429. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  430. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  431. }
  432. };
  433. template <class Derived>
  434. struct DestroyNRVOVariable : EHScopeStack::Cleanup {
  435. DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
  436. : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
  437. llvm::Value *NRVOFlag;
  438. Address Loc;
  439. QualType Ty;
  440. void Emit(CodeGenFunction &CGF, Flags flags) override {
  441. // Along the exceptions path we always execute the dtor.
  442. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  443. llvm::BasicBlock *SkipDtorBB = nullptr;
  444. if (NRVO) {
  445. // If we exited via NRVO, we skip the destructor call.
  446. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  447. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  448. llvm::Value *DidNRVO =
  449. CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
  450. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  451. CGF.EmitBlock(RunDtorBB);
  452. }
  453. static_cast<Derived *>(this)->emitDestructorCall(CGF);
  454. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  455. }
  456. virtual ~DestroyNRVOVariable() = default;
  457. };
  458. struct DestroyNRVOVariableCXX final
  459. : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
  460. DestroyNRVOVariableCXX(Address addr, QualType type,
  461. const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
  462. : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
  463. Dtor(Dtor) {}
  464. const CXXDestructorDecl *Dtor;
  465. void emitDestructorCall(CodeGenFunction &CGF) {
  466. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  467. /*ForVirtualBase=*/false,
  468. /*Delegating=*/false, Loc, Ty);
  469. }
  470. };
  471. struct DestroyNRVOVariableC final
  472. : DestroyNRVOVariable<DestroyNRVOVariableC> {
  473. DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
  474. : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
  475. void emitDestructorCall(CodeGenFunction &CGF) {
  476. CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
  477. }
  478. };
  479. struct CallStackRestore final : EHScopeStack::Cleanup {
  480. Address Stack;
  481. CallStackRestore(Address Stack) : Stack(Stack) {}
  482. bool isRedundantBeforeReturn() override { return true; }
  483. void Emit(CodeGenFunction &CGF, Flags flags) override {
  484. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  485. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  486. CGF.Builder.CreateCall(F, V);
  487. }
  488. };
  489. struct ExtendGCLifetime final : EHScopeStack::Cleanup {
  490. const VarDecl &Var;
  491. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  492. void Emit(CodeGenFunction &CGF, Flags flags) override {
  493. // Compute the address of the local variable, in case it's a
  494. // byref or something.
  495. DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
  496. Var.getType(), VK_LValue, SourceLocation());
  497. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
  498. SourceLocation());
  499. CGF.EmitExtendGCLifetime(value);
  500. }
  501. };
  502. struct CallCleanupFunction final : EHScopeStack::Cleanup {
  503. llvm::Constant *CleanupFn;
  504. const CGFunctionInfo &FnInfo;
  505. const VarDecl &Var;
  506. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  507. const VarDecl *Var)
  508. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  509. void Emit(CodeGenFunction &CGF, Flags flags) override {
  510. DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
  511. Var.getType(), VK_LValue, SourceLocation());
  512. // Compute the address of the local variable, in case it's a byref
  513. // or something.
  514. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
  515. // In some cases, the type of the function argument will be different from
  516. // the type of the pointer. An example of this is
  517. // void f(void* arg);
  518. // __attribute__((cleanup(f))) void *g;
  519. //
  520. // To fix this we insert a bitcast here.
  521. QualType ArgTy = FnInfo.arg_begin()->type;
  522. llvm::Value *Arg =
  523. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  524. CallArgList Args;
  525. Args.add(RValue::get(Arg),
  526. CGF.getContext().getPointerType(Var.getType()));
  527. auto Callee = CGCallee::forDirect(CleanupFn);
  528. CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
  529. }
  530. };
  531. } // end anonymous namespace
  532. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  533. /// variable with lifetime.
  534. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  535. Address addr,
  536. Qualifiers::ObjCLifetime lifetime) {
  537. switch (lifetime) {
  538. case Qualifiers::OCL_None:
  539. llvm_unreachable("present but none");
  540. case Qualifiers::OCL_ExplicitNone:
  541. // nothing to do
  542. break;
  543. case Qualifiers::OCL_Strong: {
  544. CodeGenFunction::Destroyer *destroyer =
  545. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  546. ? CodeGenFunction::destroyARCStrongPrecise
  547. : CodeGenFunction::destroyARCStrongImprecise);
  548. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  549. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  550. cleanupKind & EHCleanup);
  551. break;
  552. }
  553. case Qualifiers::OCL_Autoreleasing:
  554. // nothing to do
  555. break;
  556. case Qualifiers::OCL_Weak:
  557. // __weak objects always get EH cleanups; otherwise, exceptions
  558. // could cause really nasty crashes instead of mere leaks.
  559. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  560. CodeGenFunction::destroyARCWeak,
  561. /*useEHCleanup*/ true);
  562. break;
  563. }
  564. }
  565. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  566. if (const Expr *e = dyn_cast<Expr>(s)) {
  567. // Skip the most common kinds of expressions that make
  568. // hierarchy-walking expensive.
  569. s = e = e->IgnoreParenCasts();
  570. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  571. return (ref->getDecl() == &var);
  572. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  573. const BlockDecl *block = be->getBlockDecl();
  574. for (const auto &I : block->captures()) {
  575. if (I.getVariable() == &var)
  576. return true;
  577. }
  578. }
  579. }
  580. for (const Stmt *SubStmt : s->children())
  581. // SubStmt might be null; as in missing decl or conditional of an if-stmt.
  582. if (SubStmt && isAccessedBy(var, SubStmt))
  583. return true;
  584. return false;
  585. }
  586. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  587. if (!decl) return false;
  588. if (!isa<VarDecl>(decl)) return false;
  589. const VarDecl *var = cast<VarDecl>(decl);
  590. return isAccessedBy(*var, e);
  591. }
  592. static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
  593. const LValue &destLV, const Expr *init) {
  594. bool needsCast = false;
  595. while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
  596. switch (castExpr->getCastKind()) {
  597. // Look through casts that don't require representation changes.
  598. case CK_NoOp:
  599. case CK_BitCast:
  600. case CK_BlockPointerToObjCPointerCast:
  601. needsCast = true;
  602. break;
  603. // If we find an l-value to r-value cast from a __weak variable,
  604. // emit this operation as a copy or move.
  605. case CK_LValueToRValue: {
  606. const Expr *srcExpr = castExpr->getSubExpr();
  607. if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
  608. return false;
  609. // Emit the source l-value.
  610. LValue srcLV = CGF.EmitLValue(srcExpr);
  611. // Handle a formal type change to avoid asserting.
  612. auto srcAddr = srcLV.getAddress(CGF);
  613. if (needsCast) {
  614. srcAddr = CGF.Builder.CreateElementBitCast(
  615. srcAddr, destLV.getAddress(CGF).getElementType());
  616. }
  617. // If it was an l-value, use objc_copyWeak.
  618. if (srcExpr->isLValue()) {
  619. CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
  620. } else {
  621. assert(srcExpr->isXValue());
  622. CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
  623. }
  624. return true;
  625. }
  626. // Stop at anything else.
  627. default:
  628. return false;
  629. }
  630. init = castExpr->getSubExpr();
  631. }
  632. return false;
  633. }
  634. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  635. LValue &lvalue,
  636. const VarDecl *var) {
  637. lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
  638. }
  639. void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
  640. SourceLocation Loc) {
  641. if (!SanOpts.has(SanitizerKind::NullabilityAssign))
  642. return;
  643. auto Nullability = LHS.getType()->getNullability(getContext());
  644. if (!Nullability || *Nullability != NullabilityKind::NonNull)
  645. return;
  646. // Check if the right hand side of the assignment is nonnull, if the left
  647. // hand side must be nonnull.
  648. SanitizerScope SanScope(this);
  649. llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
  650. llvm::Constant *StaticData[] = {
  651. EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
  652. llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
  653. llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
  654. EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
  655. SanitizerHandler::TypeMismatch, StaticData, RHS);
  656. }
  657. void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
  658. LValue lvalue, bool capturedByInit) {
  659. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  660. if (!lifetime) {
  661. llvm::Value *value = EmitScalarExpr(init);
  662. if (capturedByInit)
  663. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  664. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  665. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  666. return;
  667. }
  668. if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
  669. init = DIE->getExpr();
  670. // If we're emitting a value with lifetime, we have to do the
  671. // initialization *before* we leave the cleanup scopes.
  672. if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
  673. CodeGenFunction::RunCleanupsScope Scope(*this);
  674. return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
  675. }
  676. // We have to maintain the illusion that the variable is
  677. // zero-initialized. If the variable might be accessed in its
  678. // initializer, zero-initialize before running the initializer, then
  679. // actually perform the initialization with an assign.
  680. bool accessedByInit = false;
  681. if (lifetime != Qualifiers::OCL_ExplicitNone)
  682. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  683. if (accessedByInit) {
  684. LValue tempLV = lvalue;
  685. // Drill down to the __block object if necessary.
  686. if (capturedByInit) {
  687. // We can use a simple GEP for this because it can't have been
  688. // moved yet.
  689. tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
  690. cast<VarDecl>(D),
  691. /*follow*/ false));
  692. }
  693. auto ty =
  694. cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
  695. llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
  696. // If __weak, we want to use a barrier under certain conditions.
  697. if (lifetime == Qualifiers::OCL_Weak)
  698. EmitARCInitWeak(tempLV.getAddress(*this), zero);
  699. // Otherwise just do a simple store.
  700. else
  701. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  702. }
  703. // Emit the initializer.
  704. llvm::Value *value = nullptr;
  705. switch (lifetime) {
  706. case Qualifiers::OCL_None:
  707. llvm_unreachable("present but none");
  708. case Qualifiers::OCL_Strong: {
  709. if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
  710. value = EmitARCRetainScalarExpr(init);
  711. break;
  712. }
  713. // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
  714. // that we omit the retain, and causes non-autoreleased return values to be
  715. // immediately released.
  716. LLVM_FALLTHROUGH;
  717. }
  718. case Qualifiers::OCL_ExplicitNone:
  719. value = EmitARCUnsafeUnretainedScalarExpr(init);
  720. break;
  721. case Qualifiers::OCL_Weak: {
  722. // If it's not accessed by the initializer, try to emit the
  723. // initialization with a copy or move.
  724. if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
  725. return;
  726. }
  727. // No way to optimize a producing initializer into this. It's not
  728. // worth optimizing for, because the value will immediately
  729. // disappear in the common case.
  730. value = EmitScalarExpr(init);
  731. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  732. if (accessedByInit)
  733. EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
  734. else
  735. EmitARCInitWeak(lvalue.getAddress(*this), value);
  736. return;
  737. }
  738. case Qualifiers::OCL_Autoreleasing:
  739. value = EmitARCRetainAutoreleaseScalarExpr(init);
  740. break;
  741. }
  742. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  743. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  744. // If the variable might have been accessed by its initializer, we
  745. // might have to initialize with a barrier. We have to do this for
  746. // both __weak and __strong, but __weak got filtered out above.
  747. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  748. llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
  749. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  750. EmitARCRelease(oldValue, ARCImpreciseLifetime);
  751. return;
  752. }
  753. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  754. }
  755. /// Decide whether we can emit the non-zero parts of the specified initializer
  756. /// with equal or fewer than NumStores scalar stores.
  757. static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
  758. unsigned &NumStores) {
  759. // Zero and Undef never requires any extra stores.
  760. if (isa<llvm::ConstantAggregateZero>(Init) ||
  761. isa<llvm::ConstantPointerNull>(Init) ||
  762. isa<llvm::UndefValue>(Init))
  763. return true;
  764. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  765. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  766. isa<llvm::ConstantExpr>(Init))
  767. return Init->isNullValue() || NumStores--;
  768. // See if we can emit each element.
  769. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  770. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  771. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  772. if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
  773. return false;
  774. }
  775. return true;
  776. }
  777. if (llvm::ConstantDataSequential *CDS =
  778. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  779. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  780. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  781. if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
  782. return false;
  783. }
  784. return true;
  785. }
  786. // Anything else is hard and scary.
  787. return false;
  788. }
  789. /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
  790. /// the scalar stores that would be required.
  791. static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
  792. llvm::Constant *Init, Address Loc,
  793. bool isVolatile, CGBuilderTy &Builder,
  794. bool IsAutoInit) {
  795. assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
  796. "called emitStoresForInitAfterBZero for zero or undef value.");
  797. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  798. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  799. isa<llvm::ConstantExpr>(Init)) {
  800. auto *I = Builder.CreateStore(Init, Loc, isVolatile);
  801. if (IsAutoInit)
  802. I->addAnnotationMetadata("auto-init");
  803. return;
  804. }
  805. if (llvm::ConstantDataSequential *CDS =
  806. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  807. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  808. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  809. // If necessary, get a pointer to the element and emit it.
  810. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  811. emitStoresForInitAfterBZero(
  812. CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
  813. Builder, IsAutoInit);
  814. }
  815. return;
  816. }
  817. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  818. "Unknown value type!");
  819. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  820. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  821. // If necessary, get a pointer to the element and emit it.
  822. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  823. emitStoresForInitAfterBZero(CGM, Elt,
  824. Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
  825. isVolatile, Builder, IsAutoInit);
  826. }
  827. }
  828. /// Decide whether we should use bzero plus some stores to initialize a local
  829. /// variable instead of using a memcpy from a constant global. It is beneficial
  830. /// to use bzero if the global is all zeros, or mostly zeros and large.
  831. static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
  832. uint64_t GlobalSize) {
  833. // If a global is all zeros, always use a bzero.
  834. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  835. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  836. // do it if it will require 6 or fewer scalar stores.
  837. // TODO: Should budget depends on the size? Avoiding a large global warrants
  838. // plopping in more stores.
  839. unsigned StoreBudget = 6;
  840. uint64_t SizeLimit = 32;
  841. return GlobalSize > SizeLimit &&
  842. canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
  843. }
  844. /// Decide whether we should use memset to initialize a local variable instead
  845. /// of using a memcpy from a constant global. Assumes we've already decided to
  846. /// not user bzero.
  847. /// FIXME We could be more clever, as we are for bzero above, and generate
  848. /// memset followed by stores. It's unclear that's worth the effort.
  849. static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
  850. uint64_t GlobalSize,
  851. const llvm::DataLayout &DL) {
  852. uint64_t SizeLimit = 32;
  853. if (GlobalSize <= SizeLimit)
  854. return nullptr;
  855. return llvm::isBytewiseValue(Init, DL);
  856. }
  857. /// Decide whether we want to split a constant structure or array store into a
  858. /// sequence of its fields' stores. This may cost us code size and compilation
  859. /// speed, but plays better with store optimizations.
  860. static bool shouldSplitConstantStore(CodeGenModule &CGM,
  861. uint64_t GlobalByteSize) {
  862. // Don't break things that occupy more than one cacheline.
  863. uint64_t ByteSizeLimit = 64;
  864. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  865. return false;
  866. if (GlobalByteSize <= ByteSizeLimit)
  867. return true;
  868. return false;
  869. }
  870. enum class IsPattern { No, Yes };
  871. /// Generate a constant filled with either a pattern or zeroes.
  872. static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
  873. llvm::Type *Ty) {
  874. if (isPattern == IsPattern::Yes)
  875. return initializationPatternFor(CGM, Ty);
  876. else
  877. return llvm::Constant::getNullValue(Ty);
  878. }
  879. static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
  880. llvm::Constant *constant);
  881. /// Helper function for constWithPadding() to deal with padding in structures.
  882. static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
  883. IsPattern isPattern,
  884. llvm::StructType *STy,
  885. llvm::Constant *constant) {
  886. const llvm::DataLayout &DL = CGM.getDataLayout();
  887. const llvm::StructLayout *Layout = DL.getStructLayout(STy);
  888. llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
  889. unsigned SizeSoFar = 0;
  890. SmallVector<llvm::Constant *, 8> Values;
  891. bool NestedIntact = true;
  892. for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
  893. unsigned CurOff = Layout->getElementOffset(i);
  894. if (SizeSoFar < CurOff) {
  895. assert(!STy->isPacked());
  896. auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
  897. Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
  898. }
  899. llvm::Constant *CurOp;
  900. if (constant->isZeroValue())
  901. CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
  902. else
  903. CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
  904. auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
  905. if (CurOp != NewOp)
  906. NestedIntact = false;
  907. Values.push_back(NewOp);
  908. SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
  909. }
  910. unsigned TotalSize = Layout->getSizeInBytes();
  911. if (SizeSoFar < TotalSize) {
  912. auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
  913. Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
  914. }
  915. if (NestedIntact && Values.size() == STy->getNumElements())
  916. return constant;
  917. return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
  918. }
  919. /// Replace all padding bytes in a given constant with either a pattern byte or
  920. /// 0x00.
  921. static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
  922. llvm::Constant *constant) {
  923. llvm::Type *OrigTy = constant->getType();
  924. if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
  925. return constStructWithPadding(CGM, isPattern, STy, constant);
  926. if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
  927. llvm::SmallVector<llvm::Constant *, 8> Values;
  928. uint64_t Size = ArrayTy->getNumElements();
  929. if (!Size)
  930. return constant;
  931. llvm::Type *ElemTy = ArrayTy->getElementType();
  932. bool ZeroInitializer = constant->isNullValue();
  933. llvm::Constant *OpValue, *PaddedOp;
  934. if (ZeroInitializer) {
  935. OpValue = llvm::Constant::getNullValue(ElemTy);
  936. PaddedOp = constWithPadding(CGM, isPattern, OpValue);
  937. }
  938. for (unsigned Op = 0; Op != Size; ++Op) {
  939. if (!ZeroInitializer) {
  940. OpValue = constant->getAggregateElement(Op);
  941. PaddedOp = constWithPadding(CGM, isPattern, OpValue);
  942. }
  943. Values.push_back(PaddedOp);
  944. }
  945. auto *NewElemTy = Values[0]->getType();
  946. if (NewElemTy == ElemTy)
  947. return constant;
  948. auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
  949. return llvm::ConstantArray::get(NewArrayTy, Values);
  950. }
  951. // FIXME: Add handling for tail padding in vectors. Vectors don't
  952. // have padding between or inside elements, but the total amount of
  953. // data can be less than the allocated size.
  954. return constant;
  955. }
  956. Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
  957. llvm::Constant *Constant,
  958. CharUnits Align) {
  959. auto FunctionName = [&](const DeclContext *DC) -> std::string {
  960. if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
  961. if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
  962. return CC->getNameAsString();
  963. if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
  964. return CD->getNameAsString();
  965. return std::string(getMangledName(FD));
  966. } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
  967. return OM->getNameAsString();
  968. } else if (isa<BlockDecl>(DC)) {
  969. return "<block>";
  970. } else if (isa<CapturedDecl>(DC)) {
  971. return "<captured>";
  972. } else {
  973. llvm_unreachable("expected a function or method");
  974. }
  975. };
  976. // Form a simple per-variable cache of these values in case we find we
  977. // want to reuse them.
  978. llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
  979. if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
  980. auto *Ty = Constant->getType();
  981. bool isConstant = true;
  982. llvm::GlobalVariable *InsertBefore = nullptr;
  983. unsigned AS =
  984. getContext().getTargetAddressSpace(GetGlobalConstantAddressSpace());
  985. std::string Name;
  986. if (D.hasGlobalStorage())
  987. Name = getMangledName(&D).str() + ".const";
  988. else if (const DeclContext *DC = D.getParentFunctionOrMethod())
  989. Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
  990. else
  991. llvm_unreachable("local variable has no parent function or method");
  992. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  993. getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
  994. Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
  995. GV->setAlignment(Align.getAsAlign());
  996. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  997. CacheEntry = GV;
  998. } else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
  999. CacheEntry->setAlignment(Align.getAsAlign());
  1000. }
  1001. return Address(CacheEntry, CacheEntry->getValueType(), Align);
  1002. }
  1003. static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
  1004. const VarDecl &D,
  1005. CGBuilderTy &Builder,
  1006. llvm::Constant *Constant,
  1007. CharUnits Align) {
  1008. Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
  1009. llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(),
  1010. SrcPtr.getAddressSpace());
  1011. if (SrcPtr.getType() != BP)
  1012. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  1013. return SrcPtr;
  1014. }
  1015. static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
  1016. Address Loc, bool isVolatile,
  1017. CGBuilderTy &Builder,
  1018. llvm::Constant *constant, bool IsAutoInit) {
  1019. auto *Ty = constant->getType();
  1020. uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
  1021. if (!ConstantSize)
  1022. return;
  1023. bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
  1024. Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
  1025. if (canDoSingleStore) {
  1026. auto *I = Builder.CreateStore(constant, Loc, isVolatile);
  1027. if (IsAutoInit)
  1028. I->addAnnotationMetadata("auto-init");
  1029. return;
  1030. }
  1031. auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
  1032. // If the initializer is all or mostly the same, codegen with bzero / memset
  1033. // then do a few stores afterward.
  1034. if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
  1035. auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
  1036. SizeVal, isVolatile);
  1037. if (IsAutoInit)
  1038. I->addAnnotationMetadata("auto-init");
  1039. bool valueAlreadyCorrect =
  1040. constant->isNullValue() || isa<llvm::UndefValue>(constant);
  1041. if (!valueAlreadyCorrect) {
  1042. Loc = Builder.CreateElementBitCast(Loc, Ty);
  1043. emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
  1044. IsAutoInit);
  1045. }
  1046. return;
  1047. }
  1048. // If the initializer is a repeated byte pattern, use memset.
  1049. llvm::Value *Pattern =
  1050. shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
  1051. if (Pattern) {
  1052. uint64_t Value = 0x00;
  1053. if (!isa<llvm::UndefValue>(Pattern)) {
  1054. const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
  1055. assert(AP.getBitWidth() <= 8);
  1056. Value = AP.getLimitedValue();
  1057. }
  1058. auto *I = Builder.CreateMemSet(
  1059. Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
  1060. if (IsAutoInit)
  1061. I->addAnnotationMetadata("auto-init");
  1062. return;
  1063. }
  1064. // If the initializer is small, use a handful of stores.
  1065. if (shouldSplitConstantStore(CGM, ConstantSize)) {
  1066. if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
  1067. // FIXME: handle the case when STy != Loc.getElementType().
  1068. if (STy == Loc.getElementType()) {
  1069. for (unsigned i = 0; i != constant->getNumOperands(); i++) {
  1070. Address EltPtr = Builder.CreateStructGEP(Loc, i);
  1071. emitStoresForConstant(
  1072. CGM, D, EltPtr, isVolatile, Builder,
  1073. cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
  1074. IsAutoInit);
  1075. }
  1076. return;
  1077. }
  1078. } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
  1079. // FIXME: handle the case when ATy != Loc.getElementType().
  1080. if (ATy == Loc.getElementType()) {
  1081. for (unsigned i = 0; i != ATy->getNumElements(); i++) {
  1082. Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
  1083. emitStoresForConstant(
  1084. CGM, D, EltPtr, isVolatile, Builder,
  1085. cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
  1086. IsAutoInit);
  1087. }
  1088. return;
  1089. }
  1090. }
  1091. }
  1092. // Copy from a global.
  1093. auto *I =
  1094. Builder.CreateMemCpy(Loc,
  1095. createUnnamedGlobalForMemcpyFrom(
  1096. CGM, D, Builder, constant, Loc.getAlignment()),
  1097. SizeVal, isVolatile);
  1098. if (IsAutoInit)
  1099. I->addAnnotationMetadata("auto-init");
  1100. }
  1101. static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
  1102. Address Loc, bool isVolatile,
  1103. CGBuilderTy &Builder) {
  1104. llvm::Type *ElTy = Loc.getElementType();
  1105. llvm::Constant *constant =
  1106. constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
  1107. emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
  1108. /*IsAutoInit=*/true);
  1109. }
  1110. static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
  1111. Address Loc, bool isVolatile,
  1112. CGBuilderTy &Builder) {
  1113. llvm::Type *ElTy = Loc.getElementType();
  1114. llvm::Constant *constant = constWithPadding(
  1115. CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
  1116. assert(!isa<llvm::UndefValue>(constant));
  1117. emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
  1118. /*IsAutoInit=*/true);
  1119. }
  1120. static bool containsUndef(llvm::Constant *constant) {
  1121. auto *Ty = constant->getType();
  1122. if (isa<llvm::UndefValue>(constant))
  1123. return true;
  1124. if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
  1125. for (llvm::Use &Op : constant->operands())
  1126. if (containsUndef(cast<llvm::Constant>(Op)))
  1127. return true;
  1128. return false;
  1129. }
  1130. static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
  1131. llvm::Constant *constant) {
  1132. auto *Ty = constant->getType();
  1133. if (isa<llvm::UndefValue>(constant))
  1134. return patternOrZeroFor(CGM, isPattern, Ty);
  1135. if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
  1136. return constant;
  1137. if (!containsUndef(constant))
  1138. return constant;
  1139. llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
  1140. for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
  1141. auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
  1142. Values[Op] = replaceUndef(CGM, isPattern, OpValue);
  1143. }
  1144. if (Ty->isStructTy())
  1145. return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
  1146. if (Ty->isArrayTy())
  1147. return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
  1148. assert(Ty->isVectorTy());
  1149. return llvm::ConstantVector::get(Values);
  1150. }
  1151. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  1152. /// variable declaration with auto, register, or no storage class specifier.
  1153. /// These turn into simple stack objects, or GlobalValues depending on target.
  1154. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  1155. AutoVarEmission emission = EmitAutoVarAlloca(D);
  1156. EmitAutoVarInit(emission);
  1157. EmitAutoVarCleanups(emission);
  1158. }
  1159. /// Emit a lifetime.begin marker if some criteria are satisfied.
  1160. /// \return a pointer to the temporary size Value if a marker was emitted, null
  1161. /// otherwise
  1162. llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
  1163. llvm::Value *Addr) {
  1164. if (!ShouldEmitLifetimeMarkers)
  1165. return nullptr;
  1166. assert(Addr->getType()->getPointerAddressSpace() ==
  1167. CGM.getDataLayout().getAllocaAddrSpace() &&
  1168. "Pointer should be in alloca address space");
  1169. llvm::Value *SizeV = llvm::ConstantInt::get(
  1170. Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
  1171. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  1172. llvm::CallInst *C =
  1173. Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
  1174. C->setDoesNotThrow();
  1175. return SizeV;
  1176. }
  1177. void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
  1178. assert(Addr->getType()->getPointerAddressSpace() ==
  1179. CGM.getDataLayout().getAllocaAddrSpace() &&
  1180. "Pointer should be in alloca address space");
  1181. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  1182. llvm::CallInst *C =
  1183. Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
  1184. C->setDoesNotThrow();
  1185. }
  1186. void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
  1187. CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
  1188. // For each dimension stores its QualType and corresponding
  1189. // size-expression Value.
  1190. SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
  1191. SmallVector<IdentifierInfo *, 4> VLAExprNames;
  1192. // Break down the array into individual dimensions.
  1193. QualType Type1D = D.getType();
  1194. while (getContext().getAsVariableArrayType(Type1D)) {
  1195. auto VlaSize = getVLAElements1D(Type1D);
  1196. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  1197. Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
  1198. else {
  1199. // Generate a locally unique name for the size expression.
  1200. Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
  1201. SmallString<12> Buffer;
  1202. StringRef NameRef = Name.toStringRef(Buffer);
  1203. auto &Ident = getContext().Idents.getOwn(NameRef);
  1204. VLAExprNames.push_back(&Ident);
  1205. auto SizeExprAddr =
  1206. CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
  1207. Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
  1208. Dimensions.emplace_back(SizeExprAddr.getPointer(),
  1209. Type1D.getUnqualifiedType());
  1210. }
  1211. Type1D = VlaSize.Type;
  1212. }
  1213. if (!EmitDebugInfo)
  1214. return;
  1215. // Register each dimension's size-expression with a DILocalVariable,
  1216. // so that it can be used by CGDebugInfo when instantiating a DISubrange
  1217. // to describe this array.
  1218. unsigned NameIdx = 0;
  1219. for (auto &VlaSize : Dimensions) {
  1220. llvm::Metadata *MD;
  1221. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  1222. MD = llvm::ConstantAsMetadata::get(C);
  1223. else {
  1224. // Create an artificial VarDecl to generate debug info for.
  1225. IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
  1226. assert(cast<llvm::PointerType>(VlaSize.NumElts->getType())
  1227. ->isOpaqueOrPointeeTypeMatches(SizeTy) &&
  1228. "Number of VLA elements must be SizeTy");
  1229. auto QT = getContext().getIntTypeForBitwidth(
  1230. SizeTy->getScalarSizeInBits(), false);
  1231. auto *ArtificialDecl = VarDecl::Create(
  1232. getContext(), const_cast<DeclContext *>(D.getDeclContext()),
  1233. D.getLocation(), D.getLocation(), NameIdent, QT,
  1234. getContext().CreateTypeSourceInfo(QT), SC_Auto);
  1235. ArtificialDecl->setImplicit();
  1236. MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
  1237. Builder);
  1238. }
  1239. assert(MD && "No Size expression debug node created");
  1240. DI->registerVLASizeExpression(VlaSize.Type, MD);
  1241. }
  1242. }
  1243. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  1244. /// local variable. Does not emit initialization or destruction.
  1245. CodeGenFunction::AutoVarEmission
  1246. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  1247. QualType Ty = D.getType();
  1248. assert(
  1249. Ty.getAddressSpace() == LangAS::Default ||
  1250. (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
  1251. AutoVarEmission emission(D);
  1252. bool isEscapingByRef = D.isEscapingByref();
  1253. emission.IsEscapingByRef = isEscapingByRef;
  1254. CharUnits alignment = getContext().getDeclAlign(&D);
  1255. // If the type is variably-modified, emit all the VLA sizes for it.
  1256. if (Ty->isVariablyModifiedType())
  1257. EmitVariablyModifiedType(Ty);
  1258. auto *DI = getDebugInfo();
  1259. bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
  1260. Address address = Address::invalid();
  1261. Address AllocaAddr = Address::invalid();
  1262. Address OpenMPLocalAddr = Address::invalid();
  1263. if (CGM.getLangOpts().OpenMPIRBuilder)
  1264. OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
  1265. else
  1266. OpenMPLocalAddr =
  1267. getLangOpts().OpenMP
  1268. ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
  1269. : Address::invalid();
  1270. bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
  1271. if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
  1272. address = OpenMPLocalAddr;
  1273. AllocaAddr = OpenMPLocalAddr;
  1274. } else if (Ty->isConstantSizeType()) {
  1275. // If this value is an array or struct with a statically determinable
  1276. // constant initializer, there are optimizations we can do.
  1277. //
  1278. // TODO: We should constant-evaluate the initializer of any variable,
  1279. // as long as it is initialized by a constant expression. Currently,
  1280. // isConstantInitializer produces wrong answers for structs with
  1281. // reference or bitfield members, and a few other cases, and checking
  1282. // for POD-ness protects us from some of these.
  1283. if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
  1284. (D.isConstexpr() ||
  1285. ((Ty.isPODType(getContext()) ||
  1286. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  1287. D.getInit()->isConstantInitializer(getContext(), false)))) {
  1288. // If the variable's a const type, and it's neither an NRVO
  1289. // candidate nor a __block variable and has no mutable members,
  1290. // emit it as a global instead.
  1291. // Exception is if a variable is located in non-constant address space
  1292. // in OpenCL.
  1293. if ((!getLangOpts().OpenCL ||
  1294. Ty.getAddressSpace() == LangAS::opencl_constant) &&
  1295. (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
  1296. !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
  1297. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  1298. // Signal this condition to later callbacks.
  1299. emission.Addr = Address::invalid();
  1300. assert(emission.wasEmittedAsGlobal());
  1301. return emission;
  1302. }
  1303. // Otherwise, tell the initialization code that we're in this case.
  1304. emission.IsConstantAggregate = true;
  1305. }
  1306. // A normal fixed sized variable becomes an alloca in the entry block,
  1307. // unless:
  1308. // - it's an NRVO variable.
  1309. // - we are compiling OpenMP and it's an OpenMP local variable.
  1310. if (NRVO) {
  1311. // The named return value optimization: allocate this variable in the
  1312. // return slot, so that we can elide the copy when returning this
  1313. // variable (C++0x [class.copy]p34).
  1314. address = ReturnValue;
  1315. AllocaAddr = ReturnValue;
  1316. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  1317. const auto *RD = RecordTy->getDecl();
  1318. const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  1319. if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
  1320. RD->isNonTrivialToPrimitiveDestroy()) {
  1321. // Create a flag that is used to indicate when the NRVO was applied
  1322. // to this variable. Set it to zero to indicate that NRVO was not
  1323. // applied.
  1324. llvm::Value *Zero = Builder.getFalse();
  1325. Address NRVOFlag =
  1326. CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo",
  1327. /*ArraySize=*/nullptr, &AllocaAddr);
  1328. EnsureInsertPoint();
  1329. Builder.CreateStore(Zero, NRVOFlag);
  1330. // Record the NRVO flag for this variable.
  1331. NRVOFlags[&D] = NRVOFlag.getPointer();
  1332. emission.NRVOFlag = NRVOFlag.getPointer();
  1333. }
  1334. }
  1335. } else {
  1336. CharUnits allocaAlignment;
  1337. llvm::Type *allocaTy;
  1338. if (isEscapingByRef) {
  1339. auto &byrefInfo = getBlockByrefInfo(&D);
  1340. allocaTy = byrefInfo.Type;
  1341. allocaAlignment = byrefInfo.ByrefAlignment;
  1342. } else {
  1343. allocaTy = ConvertTypeForMem(Ty);
  1344. allocaAlignment = alignment;
  1345. }
  1346. // Create the alloca. Note that we set the name separately from
  1347. // building the instruction so that it's there even in no-asserts
  1348. // builds.
  1349. address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
  1350. /*ArraySize=*/nullptr, &AllocaAddr);
  1351. // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
  1352. // the catch parameter starts in the catchpad instruction, and we can't
  1353. // insert code in those basic blocks.
  1354. bool IsMSCatchParam =
  1355. D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
  1356. // Emit a lifetime intrinsic if meaningful. There's no point in doing this
  1357. // if we don't have a valid insertion point (?).
  1358. if (HaveInsertPoint() && !IsMSCatchParam) {
  1359. // If there's a jump into the lifetime of this variable, its lifetime
  1360. // gets broken up into several regions in IR, which requires more work
  1361. // to handle correctly. For now, just omit the intrinsics; this is a
  1362. // rare case, and it's better to just be conservatively correct.
  1363. // PR28267.
  1364. //
  1365. // We have to do this in all language modes if there's a jump past the
  1366. // declaration. We also have to do it in C if there's a jump to an
  1367. // earlier point in the current block because non-VLA lifetimes begin as
  1368. // soon as the containing block is entered, not when its variables
  1369. // actually come into scope; suppressing the lifetime annotations
  1370. // completely in this case is unnecessarily pessimistic, but again, this
  1371. // is rare.
  1372. if (!Bypasses.IsBypassed(&D) &&
  1373. !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
  1374. llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
  1375. emission.SizeForLifetimeMarkers =
  1376. EmitLifetimeStart(Size, AllocaAddr.getPointer());
  1377. }
  1378. } else {
  1379. assert(!emission.useLifetimeMarkers());
  1380. }
  1381. }
  1382. } else {
  1383. EnsureInsertPoint();
  1384. if (!DidCallStackSave) {
  1385. // Save the stack.
  1386. Address Stack =
  1387. CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
  1388. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  1389. llvm::Value *V = Builder.CreateCall(F);
  1390. Builder.CreateStore(V, Stack);
  1391. DidCallStackSave = true;
  1392. // Push a cleanup block and restore the stack there.
  1393. // FIXME: in general circumstances, this should be an EH cleanup.
  1394. pushStackRestore(NormalCleanup, Stack);
  1395. }
  1396. auto VlaSize = getVLASize(Ty);
  1397. llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
  1398. // Allocate memory for the array.
  1399. address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
  1400. &AllocaAddr);
  1401. // If we have debug info enabled, properly describe the VLA dimensions for
  1402. // this type by registering the vla size expression for each of the
  1403. // dimensions.
  1404. EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
  1405. }
  1406. setAddrOfLocalVar(&D, address);
  1407. emission.Addr = address;
  1408. emission.AllocaAddr = AllocaAddr;
  1409. // Emit debug info for local var declaration.
  1410. if (EmitDebugInfo && HaveInsertPoint()) {
  1411. Address DebugAddr = address;
  1412. bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
  1413. DI->setLocation(D.getLocation());
  1414. // If NRVO, use a pointer to the return address.
  1415. if (UsePointerValue) {
  1416. DebugAddr = ReturnValuePointer;
  1417. AllocaAddr = ReturnValuePointer;
  1418. }
  1419. (void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
  1420. UsePointerValue);
  1421. }
  1422. if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
  1423. EmitVarAnnotations(&D, address.getPointer());
  1424. // Make sure we call @llvm.lifetime.end.
  1425. if (emission.useLifetimeMarkers())
  1426. EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
  1427. emission.getOriginalAllocatedAddress(),
  1428. emission.getSizeForLifetimeMarkers());
  1429. return emission;
  1430. }
  1431. static bool isCapturedBy(const VarDecl &, const Expr *);
  1432. /// Determines whether the given __block variable is potentially
  1433. /// captured by the given statement.
  1434. static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
  1435. if (const Expr *E = dyn_cast<Expr>(S))
  1436. return isCapturedBy(Var, E);
  1437. for (const Stmt *SubStmt : S->children())
  1438. if (isCapturedBy(Var, SubStmt))
  1439. return true;
  1440. return false;
  1441. }
  1442. /// Determines whether the given __block variable is potentially
  1443. /// captured by the given expression.
  1444. static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
  1445. // Skip the most common kinds of expressions that make
  1446. // hierarchy-walking expensive.
  1447. E = E->IgnoreParenCasts();
  1448. if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
  1449. const BlockDecl *Block = BE->getBlockDecl();
  1450. for (const auto &I : Block->captures()) {
  1451. if (I.getVariable() == &Var)
  1452. return true;
  1453. }
  1454. // No need to walk into the subexpressions.
  1455. return false;
  1456. }
  1457. if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
  1458. const CompoundStmt *CS = SE->getSubStmt();
  1459. for (const auto *BI : CS->body())
  1460. if (const auto *BIE = dyn_cast<Expr>(BI)) {
  1461. if (isCapturedBy(Var, BIE))
  1462. return true;
  1463. }
  1464. else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
  1465. // special case declarations
  1466. for (const auto *I : DS->decls()) {
  1467. if (const auto *VD = dyn_cast<VarDecl>((I))) {
  1468. const Expr *Init = VD->getInit();
  1469. if (Init && isCapturedBy(Var, Init))
  1470. return true;
  1471. }
  1472. }
  1473. }
  1474. else
  1475. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  1476. // Later, provide code to poke into statements for capture analysis.
  1477. return true;
  1478. return false;
  1479. }
  1480. for (const Stmt *SubStmt : E->children())
  1481. if (isCapturedBy(Var, SubStmt))
  1482. return true;
  1483. return false;
  1484. }
  1485. /// Determine whether the given initializer is trivial in the sense
  1486. /// that it requires no code to be generated.
  1487. bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
  1488. if (!Init)
  1489. return true;
  1490. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  1491. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  1492. if (Constructor->isTrivial() &&
  1493. Constructor->isDefaultConstructor() &&
  1494. !Construct->requiresZeroInitialization())
  1495. return true;
  1496. return false;
  1497. }
  1498. void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
  1499. const VarDecl &D,
  1500. Address Loc) {
  1501. auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
  1502. CharUnits Size = getContext().getTypeSizeInChars(type);
  1503. bool isVolatile = type.isVolatileQualified();
  1504. if (!Size.isZero()) {
  1505. switch (trivialAutoVarInit) {
  1506. case LangOptions::TrivialAutoVarInitKind::Uninitialized:
  1507. llvm_unreachable("Uninitialized handled by caller");
  1508. case LangOptions::TrivialAutoVarInitKind::Zero:
  1509. if (CGM.stopAutoInit())
  1510. return;
  1511. emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
  1512. break;
  1513. case LangOptions::TrivialAutoVarInitKind::Pattern:
  1514. if (CGM.stopAutoInit())
  1515. return;
  1516. emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
  1517. break;
  1518. }
  1519. return;
  1520. }
  1521. // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
  1522. // them, so emit a memcpy with the VLA size to initialize each element.
  1523. // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
  1524. // will catch that code, but there exists code which generates zero-sized
  1525. // VLAs. Be nice and initialize whatever they requested.
  1526. const auto *VlaType = getContext().getAsVariableArrayType(type);
  1527. if (!VlaType)
  1528. return;
  1529. auto VlaSize = getVLASize(VlaType);
  1530. auto SizeVal = VlaSize.NumElts;
  1531. CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1532. switch (trivialAutoVarInit) {
  1533. case LangOptions::TrivialAutoVarInitKind::Uninitialized:
  1534. llvm_unreachable("Uninitialized handled by caller");
  1535. case LangOptions::TrivialAutoVarInitKind::Zero: {
  1536. if (CGM.stopAutoInit())
  1537. return;
  1538. if (!EltSize.isOne())
  1539. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
  1540. auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
  1541. SizeVal, isVolatile);
  1542. I->addAnnotationMetadata("auto-init");
  1543. break;
  1544. }
  1545. case LangOptions::TrivialAutoVarInitKind::Pattern: {
  1546. if (CGM.stopAutoInit())
  1547. return;
  1548. llvm::Type *ElTy = Loc.getElementType();
  1549. llvm::Constant *Constant = constWithPadding(
  1550. CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
  1551. CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
  1552. llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
  1553. llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
  1554. llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
  1555. llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
  1556. SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
  1557. "vla.iszerosized");
  1558. Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
  1559. EmitBlock(SetupBB);
  1560. if (!EltSize.isOne())
  1561. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
  1562. llvm::Value *BaseSizeInChars =
  1563. llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
  1564. Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
  1565. llvm::Value *End = Builder.CreateInBoundsGEP(
  1566. Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end");
  1567. llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
  1568. EmitBlock(LoopBB);
  1569. llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
  1570. Cur->addIncoming(Begin.getPointer(), OriginBB);
  1571. CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
  1572. auto *I =
  1573. Builder.CreateMemCpy(Address(Cur, CurAlign),
  1574. createUnnamedGlobalForMemcpyFrom(
  1575. CGM, D, Builder, Constant, ConstantAlign),
  1576. BaseSizeInChars, isVolatile);
  1577. I->addAnnotationMetadata("auto-init");
  1578. llvm::Value *Next =
  1579. Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
  1580. llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
  1581. Builder.CreateCondBr(Done, ContBB, LoopBB);
  1582. Cur->addIncoming(Next, LoopBB);
  1583. EmitBlock(ContBB);
  1584. } break;
  1585. }
  1586. }
  1587. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  1588. assert(emission.Variable && "emission was not valid!");
  1589. // If this was emitted as a global constant, we're done.
  1590. if (emission.wasEmittedAsGlobal()) return;
  1591. const VarDecl &D = *emission.Variable;
  1592. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
  1593. QualType type = D.getType();
  1594. // If this local has an initializer, emit it now.
  1595. const Expr *Init = D.getInit();
  1596. // If we are at an unreachable point, we don't need to emit the initializer
  1597. // unless it contains a label.
  1598. if (!HaveInsertPoint()) {
  1599. if (!Init || !ContainsLabel(Init)) return;
  1600. EnsureInsertPoint();
  1601. }
  1602. // Initialize the structure of a __block variable.
  1603. if (emission.IsEscapingByRef)
  1604. emitByrefStructureInit(emission);
  1605. // Initialize the variable here if it doesn't have a initializer and it is a
  1606. // C struct that is non-trivial to initialize or an array containing such a
  1607. // struct.
  1608. if (!Init &&
  1609. type.isNonTrivialToPrimitiveDefaultInitialize() ==
  1610. QualType::PDIK_Struct) {
  1611. LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
  1612. if (emission.IsEscapingByRef)
  1613. drillIntoBlockVariable(*this, Dst, &D);
  1614. defaultInitNonTrivialCStructVar(Dst);
  1615. return;
  1616. }
  1617. // Check whether this is a byref variable that's potentially
  1618. // captured and moved by its own initializer. If so, we'll need to
  1619. // emit the initializer first, then copy into the variable.
  1620. bool capturedByInit =
  1621. Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
  1622. bool locIsByrefHeader = !capturedByInit;
  1623. const Address Loc =
  1624. locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
  1625. // Note: constexpr already initializes everything correctly.
  1626. LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
  1627. (D.isConstexpr()
  1628. ? LangOptions::TrivialAutoVarInitKind::Uninitialized
  1629. : (D.getAttr<UninitializedAttr>()
  1630. ? LangOptions::TrivialAutoVarInitKind::Uninitialized
  1631. : getContext().getLangOpts().getTrivialAutoVarInit()));
  1632. auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
  1633. if (trivialAutoVarInit ==
  1634. LangOptions::TrivialAutoVarInitKind::Uninitialized)
  1635. return;
  1636. // Only initialize a __block's storage: we always initialize the header.
  1637. if (emission.IsEscapingByRef && !locIsByrefHeader)
  1638. Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
  1639. return emitZeroOrPatternForAutoVarInit(type, D, Loc);
  1640. };
  1641. if (isTrivialInitializer(Init))
  1642. return initializeWhatIsTechnicallyUninitialized(Loc);
  1643. llvm::Constant *constant = nullptr;
  1644. if (emission.IsConstantAggregate ||
  1645. D.mightBeUsableInConstantExpressions(getContext())) {
  1646. assert(!capturedByInit && "constant init contains a capturing block?");
  1647. constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
  1648. if (constant && !constant->isZeroValue() &&
  1649. (trivialAutoVarInit !=
  1650. LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
  1651. IsPattern isPattern =
  1652. (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
  1653. ? IsPattern::Yes
  1654. : IsPattern::No;
  1655. // C guarantees that brace-init with fewer initializers than members in
  1656. // the aggregate will initialize the rest of the aggregate as-if it were
  1657. // static initialization. In turn static initialization guarantees that
  1658. // padding is initialized to zero bits. We could instead pattern-init if D
  1659. // has any ImplicitValueInitExpr, but that seems to be unintuitive
  1660. // behavior.
  1661. constant = constWithPadding(CGM, IsPattern::No,
  1662. replaceUndef(CGM, isPattern, constant));
  1663. }
  1664. }
  1665. if (!constant) {
  1666. initializeWhatIsTechnicallyUninitialized(Loc);
  1667. LValue lv = MakeAddrLValue(Loc, type);
  1668. lv.setNonGC(true);
  1669. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  1670. }
  1671. if (!emission.IsConstantAggregate) {
  1672. // For simple scalar/complex initialization, store the value directly.
  1673. LValue lv = MakeAddrLValue(Loc, type);
  1674. lv.setNonGC(true);
  1675. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  1676. }
  1677. llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
  1678. emitStoresForConstant(
  1679. CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
  1680. type.isVolatileQualified(), Builder, constant, /*IsAutoInit=*/false);
  1681. }
  1682. /// Emit an expression as an initializer for an object (variable, field, etc.)
  1683. /// at the given location. The expression is not necessarily the normal
  1684. /// initializer for the object, and the address is not necessarily
  1685. /// its normal location.
  1686. ///
  1687. /// \param init the initializing expression
  1688. /// \param D the object to act as if we're initializing
  1689. /// \param lvalue the lvalue to initialize
  1690. /// \param capturedByInit true if \p D is a __block variable
  1691. /// whose address is potentially changed by the initializer
  1692. void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1693. LValue lvalue, bool capturedByInit) {
  1694. QualType type = D->getType();
  1695. if (type->isReferenceType()) {
  1696. RValue rvalue = EmitReferenceBindingToExpr(init);
  1697. if (capturedByInit)
  1698. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1699. EmitStoreThroughLValue(rvalue, lvalue, true);
  1700. return;
  1701. }
  1702. switch (getEvaluationKind(type)) {
  1703. case TEK_Scalar:
  1704. EmitScalarInit(init, D, lvalue, capturedByInit);
  1705. return;
  1706. case TEK_Complex: {
  1707. ComplexPairTy complex = EmitComplexExpr(init);
  1708. if (capturedByInit)
  1709. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1710. EmitStoreOfComplex(complex, lvalue, /*init*/ true);
  1711. return;
  1712. }
  1713. case TEK_Aggregate:
  1714. if (type->isAtomicType()) {
  1715. EmitAtomicInit(const_cast<Expr*>(init), lvalue);
  1716. } else {
  1717. AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
  1718. if (isa<VarDecl>(D))
  1719. Overlap = AggValueSlot::DoesNotOverlap;
  1720. else if (auto *FD = dyn_cast<FieldDecl>(D))
  1721. Overlap = getOverlapForFieldInit(FD);
  1722. // TODO: how can we delay here if D is captured by its initializer?
  1723. EmitAggExpr(init, AggValueSlot::forLValue(
  1724. lvalue, *this, AggValueSlot::IsDestructed,
  1725. AggValueSlot::DoesNotNeedGCBarriers,
  1726. AggValueSlot::IsNotAliased, Overlap));
  1727. }
  1728. return;
  1729. }
  1730. llvm_unreachable("bad evaluation kind");
  1731. }
  1732. /// Enter a destroy cleanup for the given local variable.
  1733. void CodeGenFunction::emitAutoVarTypeCleanup(
  1734. const CodeGenFunction::AutoVarEmission &emission,
  1735. QualType::DestructionKind dtorKind) {
  1736. assert(dtorKind != QualType::DK_none);
  1737. // Note that for __block variables, we want to destroy the
  1738. // original stack object, not the possibly forwarded object.
  1739. Address addr = emission.getObjectAddress(*this);
  1740. const VarDecl *var = emission.Variable;
  1741. QualType type = var->getType();
  1742. CleanupKind cleanupKind = NormalAndEHCleanup;
  1743. CodeGenFunction::Destroyer *destroyer = nullptr;
  1744. switch (dtorKind) {
  1745. case QualType::DK_none:
  1746. llvm_unreachable("no cleanup for trivially-destructible variable");
  1747. case QualType::DK_cxx_destructor:
  1748. // If there's an NRVO flag on the emission, we need a different
  1749. // cleanup.
  1750. if (emission.NRVOFlag) {
  1751. assert(!type->isArrayType());
  1752. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  1753. EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
  1754. emission.NRVOFlag);
  1755. return;
  1756. }
  1757. break;
  1758. case QualType::DK_objc_strong_lifetime:
  1759. // Suppress cleanups for pseudo-strong variables.
  1760. if (var->isARCPseudoStrong()) return;
  1761. // Otherwise, consider whether to use an EH cleanup or not.
  1762. cleanupKind = getARCCleanupKind();
  1763. // Use the imprecise destroyer by default.
  1764. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  1765. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  1766. break;
  1767. case QualType::DK_objc_weak_lifetime:
  1768. break;
  1769. case QualType::DK_nontrivial_c_struct:
  1770. destroyer = CodeGenFunction::destroyNonTrivialCStruct;
  1771. if (emission.NRVOFlag) {
  1772. assert(!type->isArrayType());
  1773. EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
  1774. emission.NRVOFlag, type);
  1775. return;
  1776. }
  1777. break;
  1778. }
  1779. // If we haven't chosen a more specific destroyer, use the default.
  1780. if (!destroyer) destroyer = getDestroyer(dtorKind);
  1781. // Use an EH cleanup in array destructors iff the destructor itself
  1782. // is being pushed as an EH cleanup.
  1783. bool useEHCleanup = (cleanupKind & EHCleanup);
  1784. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  1785. useEHCleanup);
  1786. }
  1787. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  1788. assert(emission.Variable && "emission was not valid!");
  1789. // If this was emitted as a global constant, we're done.
  1790. if (emission.wasEmittedAsGlobal()) return;
  1791. // If we don't have an insertion point, we're done. Sema prevents
  1792. // us from jumping into any of these scopes anyway.
  1793. if (!HaveInsertPoint()) return;
  1794. const VarDecl &D = *emission.Variable;
  1795. // Check the type for a cleanup.
  1796. if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
  1797. emitAutoVarTypeCleanup(emission, dtorKind);
  1798. // In GC mode, honor objc_precise_lifetime.
  1799. if (getLangOpts().getGC() != LangOptions::NonGC &&
  1800. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  1801. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  1802. }
  1803. // Handle the cleanup attribute.
  1804. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  1805. const FunctionDecl *FD = CA->getFunctionDecl();
  1806. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  1807. assert(F && "Could not find function!");
  1808. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  1809. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1810. }
  1811. // If this is a block variable, call _Block_object_destroy
  1812. // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
  1813. // mode.
  1814. if (emission.IsEscapingByRef &&
  1815. CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
  1816. BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
  1817. if (emission.Variable->getType().isObjCGCWeak())
  1818. Flags |= BLOCK_FIELD_IS_WEAK;
  1819. enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
  1820. /*LoadBlockVarAddr*/ false,
  1821. cxxDestructorCanThrow(emission.Variable->getType()));
  1822. }
  1823. }
  1824. CodeGenFunction::Destroyer *
  1825. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1826. switch (kind) {
  1827. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1828. case QualType::DK_cxx_destructor:
  1829. return destroyCXXObject;
  1830. case QualType::DK_objc_strong_lifetime:
  1831. return destroyARCStrongPrecise;
  1832. case QualType::DK_objc_weak_lifetime:
  1833. return destroyARCWeak;
  1834. case QualType::DK_nontrivial_c_struct:
  1835. return destroyNonTrivialCStruct;
  1836. }
  1837. llvm_unreachable("Unknown DestructionKind");
  1838. }
  1839. /// pushEHDestroy - Push the standard destructor for the given type as
  1840. /// an EH-only cleanup.
  1841. void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
  1842. Address addr, QualType type) {
  1843. assert(dtorKind && "cannot push destructor for trivial type");
  1844. assert(needsEHCleanup(dtorKind));
  1845. pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
  1846. }
  1847. /// pushDestroy - Push the standard destructor for the given type as
  1848. /// at least a normal cleanup.
  1849. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1850. Address addr, QualType type) {
  1851. assert(dtorKind && "cannot push destructor for trivial type");
  1852. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1853. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1854. cleanupKind & EHCleanup);
  1855. }
  1856. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
  1857. QualType type, Destroyer *destroyer,
  1858. bool useEHCleanupForArray) {
  1859. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1860. destroyer, useEHCleanupForArray);
  1861. }
  1862. void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
  1863. EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
  1864. }
  1865. void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
  1866. Address addr, QualType type,
  1867. Destroyer *destroyer,
  1868. bool useEHCleanupForArray) {
  1869. // If we're not in a conditional branch, we don't need to bother generating a
  1870. // conditional cleanup.
  1871. if (!isInConditionalBranch()) {
  1872. // Push an EH-only cleanup for the object now.
  1873. // FIXME: When popping normal cleanups, we need to keep this EH cleanup
  1874. // around in case a temporary's destructor throws an exception.
  1875. if (cleanupKind & EHCleanup)
  1876. EHStack.pushCleanup<DestroyObject>(
  1877. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
  1878. destroyer, useEHCleanupForArray);
  1879. return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
  1880. cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
  1881. }
  1882. // Otherwise, we should only destroy the object if it's been initialized.
  1883. // Re-use the active flag and saved address across both the EH and end of
  1884. // scope cleanups.
  1885. using SavedType = typename DominatingValue<Address>::saved_type;
  1886. using ConditionalCleanupType =
  1887. EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
  1888. Destroyer *, bool>;
  1889. Address ActiveFlag = createCleanupActiveFlag();
  1890. SavedType SavedAddr = saveValueInCond(addr);
  1891. if (cleanupKind & EHCleanup) {
  1892. EHStack.pushCleanup<ConditionalCleanupType>(
  1893. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
  1894. destroyer, useEHCleanupForArray);
  1895. initFullExprCleanupWithFlag(ActiveFlag);
  1896. }
  1897. pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
  1898. cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
  1899. useEHCleanupForArray);
  1900. }
  1901. /// emitDestroy - Immediately perform the destruction of the given
  1902. /// object.
  1903. ///
  1904. /// \param addr - the address of the object; a type*
  1905. /// \param type - the type of the object; if an array type, all
  1906. /// objects are destroyed in reverse order
  1907. /// \param destroyer - the function to call to destroy individual
  1908. /// elements
  1909. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1910. /// used when destroying array elements, in case one of the
  1911. /// destructions throws an exception
  1912. void CodeGenFunction::emitDestroy(Address addr, QualType type,
  1913. Destroyer *destroyer,
  1914. bool useEHCleanupForArray) {
  1915. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1916. if (!arrayType)
  1917. return destroyer(*this, addr, type);
  1918. llvm::Value *length = emitArrayLength(arrayType, type, addr);
  1919. CharUnits elementAlign =
  1920. addr.getAlignment()
  1921. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1922. // Normally we have to check whether the array is zero-length.
  1923. bool checkZeroLength = true;
  1924. // But if the array length is constant, we can suppress that.
  1925. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1926. // ...and if it's constant zero, we can just skip the entire thing.
  1927. if (constLength->isZero()) return;
  1928. checkZeroLength = false;
  1929. }
  1930. llvm::Value *begin = addr.getPointer();
  1931. llvm::Value *end =
  1932. Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
  1933. emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1934. checkZeroLength, useEHCleanupForArray);
  1935. }
  1936. /// emitArrayDestroy - Destroys all the elements of the given array,
  1937. /// beginning from last to first. The array cannot be zero-length.
  1938. ///
  1939. /// \param begin - a type* denoting the first element of the array
  1940. /// \param end - a type* denoting one past the end of the array
  1941. /// \param elementType - the element type of the array
  1942. /// \param destroyer - the function to call to destroy elements
  1943. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1944. /// the remaining elements in case the destruction of a single
  1945. /// element throws
  1946. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1947. llvm::Value *end,
  1948. QualType elementType,
  1949. CharUnits elementAlign,
  1950. Destroyer *destroyer,
  1951. bool checkZeroLength,
  1952. bool useEHCleanup) {
  1953. assert(!elementType->isArrayType());
  1954. // The basic structure here is a do-while loop, because we don't
  1955. // need to check for the zero-element case.
  1956. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1957. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1958. if (checkZeroLength) {
  1959. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1960. "arraydestroy.isempty");
  1961. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1962. }
  1963. // Enter the loop body, making that address the current address.
  1964. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1965. EmitBlock(bodyBB);
  1966. llvm::PHINode *elementPast =
  1967. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1968. elementPast->addIncoming(end, entryBB);
  1969. // Shift the address back by one element.
  1970. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1971. llvm::Type *llvmElementType = ConvertTypeForMem(elementType);
  1972. llvm::Value *element = Builder.CreateInBoundsGEP(
  1973. llvmElementType, elementPast, negativeOne, "arraydestroy.element");
  1974. if (useEHCleanup)
  1975. pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
  1976. destroyer);
  1977. // Perform the actual destruction there.
  1978. destroyer(*this, Address(element, llvmElementType, elementAlign),
  1979. elementType);
  1980. if (useEHCleanup)
  1981. PopCleanupBlock();
  1982. // Check whether we've reached the end.
  1983. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1984. Builder.CreateCondBr(done, doneBB, bodyBB);
  1985. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1986. // Done.
  1987. EmitBlock(doneBB);
  1988. }
  1989. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1990. /// emitArrayDestroy, the element type here may still be an array type.
  1991. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1992. llvm::Value *begin, llvm::Value *end,
  1993. QualType type, CharUnits elementAlign,
  1994. CodeGenFunction::Destroyer *destroyer) {
  1995. // If the element type is itself an array, drill down.
  1996. unsigned arrayDepth = 0;
  1997. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1998. // VLAs don't require a GEP index to walk into.
  1999. if (!isa<VariableArrayType>(arrayType))
  2000. arrayDepth++;
  2001. type = arrayType->getElementType();
  2002. }
  2003. if (arrayDepth) {
  2004. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  2005. SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
  2006. llvm::Type *elemTy = begin->getType()->getPointerElementType();
  2007. begin = CGF.Builder.CreateInBoundsGEP(
  2008. elemTy, begin, gepIndices, "pad.arraybegin");
  2009. end = CGF.Builder.CreateInBoundsGEP(
  2010. elemTy, end, gepIndices, "pad.arrayend");
  2011. }
  2012. // Destroy the array. We don't ever need an EH cleanup because we
  2013. // assume that we're in an EH cleanup ourselves, so a throwing
  2014. // destructor causes an immediate terminate.
  2015. CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  2016. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  2017. }
  2018. namespace {
  2019. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  2020. /// array destroy where the end pointer is regularly determined and
  2021. /// does not need to be loaded from a local.
  2022. class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  2023. llvm::Value *ArrayBegin;
  2024. llvm::Value *ArrayEnd;
  2025. QualType ElementType;
  2026. CodeGenFunction::Destroyer *Destroyer;
  2027. CharUnits ElementAlign;
  2028. public:
  2029. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  2030. QualType elementType, CharUnits elementAlign,
  2031. CodeGenFunction::Destroyer *destroyer)
  2032. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  2033. ElementType(elementType), Destroyer(destroyer),
  2034. ElementAlign(elementAlign) {}
  2035. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2036. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  2037. ElementType, ElementAlign, Destroyer);
  2038. }
  2039. };
  2040. /// IrregularPartialArrayDestroy - a cleanup which performs a
  2041. /// partial array destroy where the end pointer is irregularly
  2042. /// determined and must be loaded from a local.
  2043. class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  2044. llvm::Value *ArrayBegin;
  2045. Address ArrayEndPointer;
  2046. QualType ElementType;
  2047. CodeGenFunction::Destroyer *Destroyer;
  2048. CharUnits ElementAlign;
  2049. public:
  2050. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  2051. Address arrayEndPointer,
  2052. QualType elementType,
  2053. CharUnits elementAlign,
  2054. CodeGenFunction::Destroyer *destroyer)
  2055. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  2056. ElementType(elementType), Destroyer(destroyer),
  2057. ElementAlign(elementAlign) {}
  2058. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2059. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  2060. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  2061. ElementType, ElementAlign, Destroyer);
  2062. }
  2063. };
  2064. } // end anonymous namespace
  2065. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  2066. /// already-constructed elements of the given array. The cleanup
  2067. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  2068. ///
  2069. /// \param elementType - the immediate element type of the array;
  2070. /// possibly still an array type
  2071. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  2072. Address arrayEndPointer,
  2073. QualType elementType,
  2074. CharUnits elementAlign,
  2075. Destroyer *destroyer) {
  2076. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  2077. arrayBegin, arrayEndPointer,
  2078. elementType, elementAlign,
  2079. destroyer);
  2080. }
  2081. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  2082. /// already-constructed elements of the given array. The cleanup
  2083. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  2084. ///
  2085. /// \param elementType - the immediate element type of the array;
  2086. /// possibly still an array type
  2087. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  2088. llvm::Value *arrayEnd,
  2089. QualType elementType,
  2090. CharUnits elementAlign,
  2091. Destroyer *destroyer) {
  2092. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  2093. arrayBegin, arrayEnd,
  2094. elementType, elementAlign,
  2095. destroyer);
  2096. }
  2097. /// Lazily declare the @llvm.lifetime.start intrinsic.
  2098. llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
  2099. if (LifetimeStartFn)
  2100. return LifetimeStartFn;
  2101. LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
  2102. llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
  2103. return LifetimeStartFn;
  2104. }
  2105. /// Lazily declare the @llvm.lifetime.end intrinsic.
  2106. llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
  2107. if (LifetimeEndFn)
  2108. return LifetimeEndFn;
  2109. LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
  2110. llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
  2111. return LifetimeEndFn;
  2112. }
  2113. namespace {
  2114. /// A cleanup to perform a release of an object at the end of a
  2115. /// function. This is used to balance out the incoming +1 of a
  2116. /// ns_consumed argument when we can't reasonably do that just by
  2117. /// not doing the initial retain for a __block argument.
  2118. struct ConsumeARCParameter final : EHScopeStack::Cleanup {
  2119. ConsumeARCParameter(llvm::Value *param,
  2120. ARCPreciseLifetime_t precise)
  2121. : Param(param), Precise(precise) {}
  2122. llvm::Value *Param;
  2123. ARCPreciseLifetime_t Precise;
  2124. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2125. CGF.EmitARCRelease(Param, Precise);
  2126. }
  2127. };
  2128. } // end anonymous namespace
  2129. /// Emit an alloca (or GlobalValue depending on target)
  2130. /// for the specified parameter and set up LocalDeclMap.
  2131. void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
  2132. unsigned ArgNo) {
  2133. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  2134. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  2135. "Invalid argument to EmitParmDecl");
  2136. Arg.getAnyValue()->setName(D.getName());
  2137. QualType Ty = D.getType();
  2138. // Use better IR generation for certain implicit parameters.
  2139. if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
  2140. // The only implicit argument a block has is its literal.
  2141. // This may be passed as an inalloca'ed value on Windows x86.
  2142. if (BlockInfo) {
  2143. llvm::Value *V = Arg.isIndirect()
  2144. ? Builder.CreateLoad(Arg.getIndirectAddress())
  2145. : Arg.getDirectValue();
  2146. setBlockContextParameter(IPD, ArgNo, V);
  2147. return;
  2148. }
  2149. }
  2150. Address DeclPtr = Address::invalid();
  2151. Address AllocaPtr = Address::invalid();
  2152. bool DoStore = false;
  2153. bool IsScalar = hasScalarEvaluationKind(Ty);
  2154. // If we already have a pointer to the argument, reuse the input pointer.
  2155. if (Arg.isIndirect()) {
  2156. DeclPtr = Arg.getIndirectAddress();
  2157. // If we have a prettier pointer type at this point, bitcast to that.
  2158. unsigned AS = DeclPtr.getType()->getAddressSpace();
  2159. llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
  2160. if (DeclPtr.getType() != IRTy)
  2161. DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
  2162. // Indirect argument is in alloca address space, which may be different
  2163. // from the default address space.
  2164. auto AllocaAS = CGM.getASTAllocaAddressSpace();
  2165. auto *V = DeclPtr.getPointer();
  2166. AllocaPtr = DeclPtr;
  2167. auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
  2168. auto DestLangAS =
  2169. getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
  2170. if (SrcLangAS != DestLangAS) {
  2171. assert(getContext().getTargetAddressSpace(SrcLangAS) ==
  2172. CGM.getDataLayout().getAllocaAddrSpace());
  2173. auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
  2174. auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
  2175. DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
  2176. *this, V, SrcLangAS, DestLangAS, T, true),
  2177. DeclPtr.getAlignment());
  2178. }
  2179. // Push a destructor cleanup for this parameter if the ABI requires it.
  2180. // Don't push a cleanup in a thunk for a method that will also emit a
  2181. // cleanup.
  2182. if (Ty->isRecordType() && !CurFuncIsThunk &&
  2183. Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
  2184. if (QualType::DestructionKind DtorKind =
  2185. D.needsDestruction(getContext())) {
  2186. assert((DtorKind == QualType::DK_cxx_destructor ||
  2187. DtorKind == QualType::DK_nontrivial_c_struct) &&
  2188. "unexpected destructor type");
  2189. pushDestroy(DtorKind, DeclPtr, Ty);
  2190. CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
  2191. EHStack.stable_begin();
  2192. }
  2193. }
  2194. } else {
  2195. // Check if the parameter address is controlled by OpenMP runtime.
  2196. Address OpenMPLocalAddr =
  2197. getLangOpts().OpenMP
  2198. ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
  2199. : Address::invalid();
  2200. if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
  2201. DeclPtr = OpenMPLocalAddr;
  2202. AllocaPtr = DeclPtr;
  2203. } else {
  2204. // Otherwise, create a temporary to hold the value.
  2205. DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
  2206. D.getName() + ".addr", &AllocaPtr);
  2207. }
  2208. DoStore = true;
  2209. }
  2210. llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
  2211. LValue lv = MakeAddrLValue(DeclPtr, Ty);
  2212. if (IsScalar) {
  2213. Qualifiers qs = Ty.getQualifiers();
  2214. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  2215. // We honor __attribute__((ns_consumed)) for types with lifetime.
  2216. // For __strong, it's handled by just skipping the initial retain;
  2217. // otherwise we have to balance out the initial +1 with an extra
  2218. // cleanup to do the release at the end of the function.
  2219. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  2220. // If a parameter is pseudo-strong then we can omit the implicit retain.
  2221. if (D.isARCPseudoStrong()) {
  2222. assert(lt == Qualifiers::OCL_Strong &&
  2223. "pseudo-strong variable isn't strong?");
  2224. assert(qs.hasConst() && "pseudo-strong variable should be const!");
  2225. lt = Qualifiers::OCL_ExplicitNone;
  2226. }
  2227. // Load objects passed indirectly.
  2228. if (Arg.isIndirect() && !ArgVal)
  2229. ArgVal = Builder.CreateLoad(DeclPtr);
  2230. if (lt == Qualifiers::OCL_Strong) {
  2231. if (!isConsumed) {
  2232. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  2233. // use objc_storeStrong(&dest, value) for retaining the
  2234. // object. But first, store a null into 'dest' because
  2235. // objc_storeStrong attempts to release its old value.
  2236. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  2237. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  2238. EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
  2239. DoStore = false;
  2240. }
  2241. else
  2242. // Don't use objc_retainBlock for block pointers, because we
  2243. // don't want to Block_copy something just because we got it
  2244. // as a parameter.
  2245. ArgVal = EmitARCRetainNonBlock(ArgVal);
  2246. }
  2247. } else {
  2248. // Push the cleanup for a consumed parameter.
  2249. if (isConsumed) {
  2250. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  2251. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  2252. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
  2253. precise);
  2254. }
  2255. if (lt == Qualifiers::OCL_Weak) {
  2256. EmitARCInitWeak(DeclPtr, ArgVal);
  2257. DoStore = false; // The weak init is a store, no need to do two.
  2258. }
  2259. }
  2260. // Enter the cleanup scope.
  2261. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  2262. }
  2263. }
  2264. // Store the initial value into the alloca.
  2265. if (DoStore)
  2266. EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
  2267. setAddrOfLocalVar(&D, DeclPtr);
  2268. // Emit debug info for param declarations in non-thunk functions.
  2269. if (CGDebugInfo *DI = getDebugInfo()) {
  2270. if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk) {
  2271. llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
  2272. &D, AllocaPtr.getPointer(), ArgNo, Builder);
  2273. if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
  2274. DI->getParamDbgMappings().insert({Var, DILocalVar});
  2275. }
  2276. }
  2277. if (D.hasAttr<AnnotateAttr>())
  2278. EmitVarAnnotations(&D, DeclPtr.getPointer());
  2279. // We can only check return value nullability if all arguments to the
  2280. // function satisfy their nullability preconditions. This makes it necessary
  2281. // to emit null checks for args in the function body itself.
  2282. if (requiresReturnValueNullabilityCheck()) {
  2283. auto Nullability = Ty->getNullability(getContext());
  2284. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  2285. SanitizerScope SanScope(this);
  2286. RetValNullabilityPrecondition =
  2287. Builder.CreateAnd(RetValNullabilityPrecondition,
  2288. Builder.CreateIsNotNull(Arg.getAnyValue()));
  2289. }
  2290. }
  2291. }
  2292. void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  2293. CodeGenFunction *CGF) {
  2294. if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
  2295. return;
  2296. getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
  2297. }
  2298. void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
  2299. CodeGenFunction *CGF) {
  2300. if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
  2301. (!LangOpts.EmitAllDecls && !D->isUsed()))
  2302. return;
  2303. getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
  2304. }
  2305. void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
  2306. getOpenMPRuntime().processRequiresDirective(D);
  2307. }
  2308. void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
  2309. for (const Expr *E : D->varlists()) {
  2310. const auto *DE = cast<DeclRefExpr>(E);
  2311. const auto *VD = cast<VarDecl>(DE->getDecl());
  2312. // Skip all but globals.
  2313. if (!VD->hasGlobalStorage())
  2314. continue;
  2315. // Check if the global has been materialized yet or not. If not, we are done
  2316. // as any later generation will utilize the OMPAllocateDeclAttr. However, if
  2317. // we already emitted the global we might have done so before the
  2318. // OMPAllocateDeclAttr was attached, leading to the wrong address space
  2319. // (potentially). While not pretty, common practise is to remove the old IR
  2320. // global and generate a new one, so we do that here too. Uses are replaced
  2321. // properly.
  2322. StringRef MangledName = getMangledName(VD);
  2323. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2324. if (!Entry)
  2325. continue;
  2326. // We can also keep the existing global if the address space is what we
  2327. // expect it to be, if not, it is replaced.
  2328. QualType ASTTy = VD->getType();
  2329. clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);
  2330. auto TargetAS = getContext().getTargetAddressSpace(GVAS);
  2331. if (Entry->getType()->getAddressSpace() == TargetAS)
  2332. continue;
  2333. // Make a new global with the correct type / address space.
  2334. llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
  2335. llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
  2336. // Replace all uses of the old global with a cast. Since we mutate the type
  2337. // in place we neeed an intermediate that takes the spot of the old entry
  2338. // until we can create the cast.
  2339. llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
  2340. getModule(), Entry->getValueType(), false,
  2341. llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
  2342. llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
  2343. Entry->replaceAllUsesWith(DummyGV);
  2344. Entry->mutateType(PTy);
  2345. llvm::Constant *NewPtrForOldDecl =
  2346. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  2347. Entry, DummyGV->getType());
  2348. // Now we have a casted version of the changed global, the dummy can be
  2349. // replaced and deleted.
  2350. DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
  2351. DummyGV->eraseFromParent();
  2352. }
  2353. }