CGDecl.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Decl nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "CGOpenCLRuntime.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Basic/TargetInfo.h"
  23. #include "clang/Frontend/CodeGenOptions.h"
  24. #include "llvm/GlobalVariable.h"
  25. #include "llvm/Intrinsics.h"
  26. #include "llvm/Target/TargetData.h"
  27. #include "llvm/Type.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. void CodeGenFunction::EmitDecl(const Decl &D) {
  31. switch (D.getKind()) {
  32. case Decl::TranslationUnit:
  33. case Decl::Namespace:
  34. case Decl::UnresolvedUsingTypename:
  35. case Decl::ClassTemplateSpecialization:
  36. case Decl::ClassTemplatePartialSpecialization:
  37. case Decl::TemplateTypeParm:
  38. case Decl::UnresolvedUsingValue:
  39. case Decl::NonTypeTemplateParm:
  40. case Decl::CXXMethod:
  41. case Decl::CXXConstructor:
  42. case Decl::CXXDestructor:
  43. case Decl::CXXConversion:
  44. case Decl::Field:
  45. case Decl::IndirectField:
  46. case Decl::ObjCIvar:
  47. case Decl::ObjCAtDefsField:
  48. case Decl::ParmVar:
  49. case Decl::ImplicitParam:
  50. case Decl::ClassTemplate:
  51. case Decl::FunctionTemplate:
  52. case Decl::TypeAliasTemplate:
  53. case Decl::TemplateTemplateParm:
  54. case Decl::ObjCMethod:
  55. case Decl::ObjCCategory:
  56. case Decl::ObjCProtocol:
  57. case Decl::ObjCInterface:
  58. case Decl::ObjCCategoryImpl:
  59. case Decl::ObjCImplementation:
  60. case Decl::ObjCProperty:
  61. case Decl::ObjCCompatibleAlias:
  62. case Decl::AccessSpec:
  63. case Decl::LinkageSpec:
  64. case Decl::ObjCPropertyImpl:
  65. case Decl::FileScopeAsm:
  66. case Decl::Friend:
  67. case Decl::FriendTemplate:
  68. case Decl::Block:
  69. case Decl::ClassScopeFunctionSpecialization:
  70. llvm_unreachable("Declaration should not be in declstmts!");
  71. case Decl::Function: // void X();
  72. case Decl::Record: // struct/union/class X;
  73. case Decl::Enum: // enum X;
  74. case Decl::EnumConstant: // enum ? { X = ? }
  75. case Decl::CXXRecord: // struct/union/class X; [C++]
  76. case Decl::Using: // using X; [C++]
  77. case Decl::UsingShadow:
  78. case Decl::UsingDirective: // using namespace X; [C++]
  79. case Decl::NamespaceAlias:
  80. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  81. case Decl::Label: // __label__ x;
  82. case Decl::Import:
  83. // None of these decls require codegen support.
  84. return;
  85. case Decl::Var: {
  86. const VarDecl &VD = cast<VarDecl>(D);
  87. assert(VD.isLocalVarDecl() &&
  88. "Should not see file-scope variables inside a function!");
  89. return EmitVarDecl(VD);
  90. }
  91. case Decl::Typedef: // typedef int X;
  92. case Decl::TypeAlias: { // using X = int; [C++0x]
  93. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  94. QualType Ty = TD.getUnderlyingType();
  95. if (Ty->isVariablyModifiedType())
  96. EmitVariablyModifiedType(Ty);
  97. }
  98. }
  99. }
  100. /// EmitVarDecl - This method handles emission of any variable declaration
  101. /// inside a function, including static vars etc.
  102. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  103. switch (D.getStorageClass()) {
  104. case SC_None:
  105. case SC_Auto:
  106. case SC_Register:
  107. return EmitAutoVarDecl(D);
  108. case SC_Static: {
  109. llvm::GlobalValue::LinkageTypes Linkage =
  110. llvm::GlobalValue::InternalLinkage;
  111. // If the function definition has some sort of weak linkage, its
  112. // static variables should also be weak so that they get properly
  113. // uniqued. We can't do this in C, though, because there's no
  114. // standard way to agree on which variables are the same (i.e.
  115. // there's no mangling).
  116. if (getContext().getLangOptions().CPlusPlus)
  117. if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
  118. Linkage = CurFn->getLinkage();
  119. return EmitStaticVarDecl(D, Linkage);
  120. }
  121. case SC_Extern:
  122. case SC_PrivateExtern:
  123. // Don't emit it now, allow it to be emitted lazily on its first use.
  124. return;
  125. case SC_OpenCLWorkGroupLocal:
  126. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  127. }
  128. llvm_unreachable("Unknown storage class");
  129. }
  130. static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
  131. const char *Separator) {
  132. CodeGenModule &CGM = CGF.CGM;
  133. if (CGF.getContext().getLangOptions().CPlusPlus) {
  134. StringRef Name = CGM.getMangledName(&D);
  135. return Name.str();
  136. }
  137. std::string ContextName;
  138. if (!CGF.CurFuncDecl) {
  139. // Better be in a block declared in global scope.
  140. const NamedDecl *ND = cast<NamedDecl>(&D);
  141. const DeclContext *DC = ND->getDeclContext();
  142. if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
  143. MangleBuffer Name;
  144. CGM.getBlockMangledName(GlobalDecl(), Name, BD);
  145. ContextName = Name.getString();
  146. }
  147. else
  148. llvm_unreachable("Unknown context for block static var decl");
  149. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
  150. StringRef Name = CGM.getMangledName(FD);
  151. ContextName = Name.str();
  152. } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
  153. ContextName = CGF.CurFn->getName();
  154. else
  155. llvm_unreachable("Unknown context for static var decl");
  156. return ContextName + Separator + D.getNameAsString();
  157. }
  158. llvm::GlobalVariable *
  159. CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
  160. const char *Separator,
  161. llvm::GlobalValue::LinkageTypes Linkage) {
  162. QualType Ty = D.getType();
  163. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  164. // Use the label if the variable is renamed with the asm-label extension.
  165. std::string Name;
  166. if (D.hasAttr<AsmLabelAttr>())
  167. Name = CGM.getMangledName(&D);
  168. else
  169. Name = GetStaticDeclName(*this, D, Separator);
  170. llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
  171. llvm::GlobalVariable *GV =
  172. new llvm::GlobalVariable(CGM.getModule(), LTy,
  173. Ty.isConstant(getContext()), Linkage,
  174. CGM.EmitNullConstant(D.getType()), Name, 0,
  175. D.isThreadSpecified(),
  176. CGM.getContext().getTargetAddressSpace(Ty));
  177. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  178. if (Linkage != llvm::GlobalValue::InternalLinkage)
  179. GV->setVisibility(CurFn->getVisibility());
  180. return GV;
  181. }
  182. /// hasNontrivialDestruction - Determine whether a type's destruction is
  183. /// non-trivial. If so, and the variable uses static initialization, we must
  184. /// register its destructor to run on exit.
  185. static bool hasNontrivialDestruction(QualType T) {
  186. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  187. return RD && !RD->hasTrivialDestructor();
  188. }
  189. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  190. /// global variable that has already been created for it. If the initializer
  191. /// has a different type than GV does, this may free GV and return a different
  192. /// one. Otherwise it just returns GV.
  193. llvm::GlobalVariable *
  194. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  195. llvm::GlobalVariable *GV) {
  196. llvm::Constant *Init = CGM.EmitConstantInit(D, this);
  197. // If constant emission failed, then this should be a C++ static
  198. // initializer.
  199. if (!Init) {
  200. if (!getContext().getLangOptions().CPlusPlus)
  201. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  202. else if (Builder.GetInsertBlock()) {
  203. // Since we have a static initializer, this global variable can't
  204. // be constant.
  205. GV->setConstant(false);
  206. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  207. }
  208. return GV;
  209. }
  210. // The initializer may differ in type from the global. Rewrite
  211. // the global to match the initializer. (We have to do this
  212. // because some types, like unions, can't be completely represented
  213. // in the LLVM type system.)
  214. if (GV->getType()->getElementType() != Init->getType()) {
  215. llvm::GlobalVariable *OldGV = GV;
  216. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  217. OldGV->isConstant(),
  218. OldGV->getLinkage(), Init, "",
  219. /*InsertBefore*/ OldGV,
  220. D.isThreadSpecified(),
  221. CGM.getContext().getTargetAddressSpace(D.getType()));
  222. GV->setVisibility(OldGV->getVisibility());
  223. // Steal the name of the old global
  224. GV->takeName(OldGV);
  225. // Replace all uses of the old global with the new global
  226. llvm::Constant *NewPtrForOldDecl =
  227. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  228. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  229. // Erase the old global, since it is no longer used.
  230. OldGV->eraseFromParent();
  231. }
  232. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  233. GV->setInitializer(Init);
  234. if (hasNontrivialDestruction(D.getType())) {
  235. // We have a constant initializer, but a nontrivial destructor. We still
  236. // need to perform a guarded "initialization" in order to register the
  237. // destructor.
  238. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  239. }
  240. return GV;
  241. }
  242. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  243. llvm::GlobalValue::LinkageTypes Linkage) {
  244. llvm::Value *&DMEntry = LocalDeclMap[&D];
  245. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  246. llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
  247. // Store into LocalDeclMap before generating initializer to handle
  248. // circular references.
  249. DMEntry = GV;
  250. // We can't have a VLA here, but we can have a pointer to a VLA,
  251. // even though that doesn't really make any sense.
  252. // Make sure to evaluate VLA bounds now so that we have them for later.
  253. if (D.getType()->isVariablyModifiedType())
  254. EmitVariablyModifiedType(D.getType());
  255. // Local static block variables must be treated as globals as they may be
  256. // referenced in their RHS initializer block-literal expresion.
  257. CGM.setStaticLocalDeclAddress(&D, GV);
  258. // If this value has an initializer, emit it.
  259. if (D.getInit())
  260. GV = AddInitializerToStaticVarDecl(D, GV);
  261. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  262. if (D.hasAttr<AnnotateAttr>())
  263. CGM.AddGlobalAnnotations(&D, GV);
  264. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  265. GV->setSection(SA->getName());
  266. if (D.hasAttr<UsedAttr>())
  267. CGM.AddUsedGlobal(GV);
  268. // We may have to cast the constant because of the initializer
  269. // mismatch above.
  270. //
  271. // FIXME: It is really dangerous to store this in the map; if anyone
  272. // RAUW's the GV uses of this constant will be invalid.
  273. llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
  274. llvm::Type *LPtrTy =
  275. LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
  276. DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
  277. // Emit global variable debug descriptor for static vars.
  278. CGDebugInfo *DI = getDebugInfo();
  279. if (DI) {
  280. DI->setLocation(D.getLocation());
  281. DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
  282. }
  283. }
  284. namespace {
  285. struct DestroyObject : EHScopeStack::Cleanup {
  286. DestroyObject(llvm::Value *addr, QualType type,
  287. CodeGenFunction::Destroyer *destroyer,
  288. bool useEHCleanupForArray)
  289. : addr(addr), type(type), destroyer(destroyer),
  290. useEHCleanupForArray(useEHCleanupForArray) {}
  291. llvm::Value *addr;
  292. QualType type;
  293. CodeGenFunction::Destroyer *destroyer;
  294. bool useEHCleanupForArray;
  295. void Emit(CodeGenFunction &CGF, Flags flags) {
  296. // Don't use an EH cleanup recursively from an EH cleanup.
  297. bool useEHCleanupForArray =
  298. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  299. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  300. }
  301. };
  302. struct DestroyNRVOVariable : EHScopeStack::Cleanup {
  303. DestroyNRVOVariable(llvm::Value *addr,
  304. const CXXDestructorDecl *Dtor,
  305. llvm::Value *NRVOFlag)
  306. : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
  307. const CXXDestructorDecl *Dtor;
  308. llvm::Value *NRVOFlag;
  309. llvm::Value *Loc;
  310. void Emit(CodeGenFunction &CGF, Flags flags) {
  311. // Along the exceptions path we always execute the dtor.
  312. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  313. llvm::BasicBlock *SkipDtorBB = 0;
  314. if (NRVO) {
  315. // If we exited via NRVO, we skip the destructor call.
  316. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  317. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  318. llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
  319. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  320. CGF.EmitBlock(RunDtorBB);
  321. }
  322. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  323. /*ForVirtualBase=*/false, Loc);
  324. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  325. }
  326. };
  327. struct CallStackRestore : EHScopeStack::Cleanup {
  328. llvm::Value *Stack;
  329. CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
  330. void Emit(CodeGenFunction &CGF, Flags flags) {
  331. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  332. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  333. CGF.Builder.CreateCall(F, V);
  334. }
  335. };
  336. struct ExtendGCLifetime : EHScopeStack::Cleanup {
  337. const VarDecl &Var;
  338. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  339. void Emit(CodeGenFunction &CGF, Flags flags) {
  340. // Compute the address of the local variable, in case it's a
  341. // byref or something.
  342. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
  343. SourceLocation());
  344. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
  345. CGF.EmitExtendGCLifetime(value);
  346. }
  347. };
  348. struct CallCleanupFunction : EHScopeStack::Cleanup {
  349. llvm::Constant *CleanupFn;
  350. const CGFunctionInfo &FnInfo;
  351. const VarDecl &Var;
  352. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  353. const VarDecl *Var)
  354. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  355. void Emit(CodeGenFunction &CGF, Flags flags) {
  356. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
  357. SourceLocation());
  358. // Compute the address of the local variable, in case it's a byref
  359. // or something.
  360. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
  361. // In some cases, the type of the function argument will be different from
  362. // the type of the pointer. An example of this is
  363. // void f(void* arg);
  364. // __attribute__((cleanup(f))) void *g;
  365. //
  366. // To fix this we insert a bitcast here.
  367. QualType ArgTy = FnInfo.arg_begin()->type;
  368. llvm::Value *Arg =
  369. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  370. CallArgList Args;
  371. Args.add(RValue::get(Arg),
  372. CGF.getContext().getPointerType(Var.getType()));
  373. CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
  374. }
  375. };
  376. }
  377. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  378. /// variable with lifetime.
  379. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  380. llvm::Value *addr,
  381. Qualifiers::ObjCLifetime lifetime) {
  382. switch (lifetime) {
  383. case Qualifiers::OCL_None:
  384. llvm_unreachable("present but none");
  385. case Qualifiers::OCL_ExplicitNone:
  386. // nothing to do
  387. break;
  388. case Qualifiers::OCL_Strong: {
  389. CodeGenFunction::Destroyer *destroyer =
  390. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  391. ? CodeGenFunction::destroyARCStrongPrecise
  392. : CodeGenFunction::destroyARCStrongImprecise);
  393. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  394. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  395. cleanupKind & EHCleanup);
  396. break;
  397. }
  398. case Qualifiers::OCL_Autoreleasing:
  399. // nothing to do
  400. break;
  401. case Qualifiers::OCL_Weak:
  402. // __weak objects always get EH cleanups; otherwise, exceptions
  403. // could cause really nasty crashes instead of mere leaks.
  404. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  405. CodeGenFunction::destroyARCWeak,
  406. /*useEHCleanup*/ true);
  407. break;
  408. }
  409. }
  410. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  411. if (const Expr *e = dyn_cast<Expr>(s)) {
  412. // Skip the most common kinds of expressions that make
  413. // hierarchy-walking expensive.
  414. s = e = e->IgnoreParenCasts();
  415. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  416. return (ref->getDecl() == &var);
  417. }
  418. for (Stmt::const_child_range children = s->children(); children; ++children)
  419. // children might be null; as in missing decl or conditional of an if-stmt.
  420. if ((*children) && isAccessedBy(var, *children))
  421. return true;
  422. return false;
  423. }
  424. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  425. if (!decl) return false;
  426. if (!isa<VarDecl>(decl)) return false;
  427. const VarDecl *var = cast<VarDecl>(decl);
  428. return isAccessedBy(*var, e);
  429. }
  430. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  431. LValue &lvalue,
  432. const VarDecl *var) {
  433. lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
  434. }
  435. void CodeGenFunction::EmitScalarInit(const Expr *init,
  436. const ValueDecl *D,
  437. LValue lvalue,
  438. bool capturedByInit) {
  439. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  440. if (!lifetime) {
  441. llvm::Value *value = EmitScalarExpr(init);
  442. if (capturedByInit)
  443. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  444. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  445. return;
  446. }
  447. // If we're emitting a value with lifetime, we have to do the
  448. // initialization *before* we leave the cleanup scopes.
  449. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  450. enterFullExpression(ewc);
  451. init = ewc->getSubExpr();
  452. }
  453. CodeGenFunction::RunCleanupsScope Scope(*this);
  454. // We have to maintain the illusion that the variable is
  455. // zero-initialized. If the variable might be accessed in its
  456. // initializer, zero-initialize before running the initializer, then
  457. // actually perform the initialization with an assign.
  458. bool accessedByInit = false;
  459. if (lifetime != Qualifiers::OCL_ExplicitNone)
  460. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  461. if (accessedByInit) {
  462. LValue tempLV = lvalue;
  463. // Drill down to the __block object if necessary.
  464. if (capturedByInit) {
  465. // We can use a simple GEP for this because it can't have been
  466. // moved yet.
  467. tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
  468. getByRefValueLLVMField(cast<VarDecl>(D))));
  469. }
  470. llvm::PointerType *ty
  471. = cast<llvm::PointerType>(tempLV.getAddress()->getType());
  472. ty = cast<llvm::PointerType>(ty->getElementType());
  473. llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
  474. // If __weak, we want to use a barrier under certain conditions.
  475. if (lifetime == Qualifiers::OCL_Weak)
  476. EmitARCInitWeak(tempLV.getAddress(), zero);
  477. // Otherwise just do a simple store.
  478. else
  479. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  480. }
  481. // Emit the initializer.
  482. llvm::Value *value = 0;
  483. switch (lifetime) {
  484. case Qualifiers::OCL_None:
  485. llvm_unreachable("present but none");
  486. case Qualifiers::OCL_ExplicitNone:
  487. // nothing to do
  488. value = EmitScalarExpr(init);
  489. break;
  490. case Qualifiers::OCL_Strong: {
  491. value = EmitARCRetainScalarExpr(init);
  492. break;
  493. }
  494. case Qualifiers::OCL_Weak: {
  495. // No way to optimize a producing initializer into this. It's not
  496. // worth optimizing for, because the value will immediately
  497. // disappear in the common case.
  498. value = EmitScalarExpr(init);
  499. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  500. if (accessedByInit)
  501. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  502. else
  503. EmitARCInitWeak(lvalue.getAddress(), value);
  504. return;
  505. }
  506. case Qualifiers::OCL_Autoreleasing:
  507. value = EmitARCRetainAutoreleaseScalarExpr(init);
  508. break;
  509. }
  510. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  511. // If the variable might have been accessed by its initializer, we
  512. // might have to initialize with a barrier. We have to do this for
  513. // both __weak and __strong, but __weak got filtered out above.
  514. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  515. llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
  516. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  517. EmitARCRelease(oldValue, /*precise*/ false);
  518. return;
  519. }
  520. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  521. }
  522. /// EmitScalarInit - Initialize the given lvalue with the given object.
  523. void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
  524. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  525. if (!lifetime)
  526. return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
  527. switch (lifetime) {
  528. case Qualifiers::OCL_None:
  529. llvm_unreachable("present but none");
  530. case Qualifiers::OCL_ExplicitNone:
  531. // nothing to do
  532. break;
  533. case Qualifiers::OCL_Strong:
  534. init = EmitARCRetain(lvalue.getType(), init);
  535. break;
  536. case Qualifiers::OCL_Weak:
  537. // Initialize and then skip the primitive store.
  538. EmitARCInitWeak(lvalue.getAddress(), init);
  539. return;
  540. case Qualifiers::OCL_Autoreleasing:
  541. init = EmitARCRetainAutorelease(lvalue.getType(), init);
  542. break;
  543. }
  544. EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
  545. }
  546. /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
  547. /// non-zero parts of the specified initializer with equal or fewer than
  548. /// NumStores scalar stores.
  549. static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
  550. unsigned &NumStores) {
  551. // Zero and Undef never requires any extra stores.
  552. if (isa<llvm::ConstantAggregateZero>(Init) ||
  553. isa<llvm::ConstantPointerNull>(Init) ||
  554. isa<llvm::UndefValue>(Init))
  555. return true;
  556. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  557. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  558. isa<llvm::ConstantExpr>(Init))
  559. return Init->isNullValue() || NumStores--;
  560. // See if we can emit each element.
  561. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  562. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  563. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  564. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  565. return false;
  566. }
  567. return true;
  568. }
  569. if (llvm::ConstantDataSequential *CDS =
  570. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  571. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  572. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  573. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  574. return false;
  575. }
  576. return true;
  577. }
  578. // Anything else is hard and scary.
  579. return false;
  580. }
  581. /// emitStoresForInitAfterMemset - For inits that
  582. /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
  583. /// stores that would be required.
  584. static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
  585. bool isVolatile, CGBuilderTy &Builder) {
  586. // Zero doesn't require a store.
  587. if (Init->isNullValue() || isa<llvm::UndefValue>(Init))
  588. return;
  589. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  590. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  591. isa<llvm::ConstantExpr>(Init)) {
  592. Builder.CreateStore(Init, Loc, isVolatile);
  593. return;
  594. }
  595. if (llvm::ConstantDataSequential *CDS =
  596. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  597. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  598. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  599. // Get a pointer to the element and emit it.
  600. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  601. isVolatile, Builder);
  602. }
  603. return;
  604. }
  605. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  606. "Unknown value type!");
  607. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  608. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  609. // Get a pointer to the element and emit it.
  610. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  611. isVolatile, Builder);
  612. }
  613. }
  614. /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
  615. /// plus some stores to initialize a local variable instead of using a memcpy
  616. /// from a constant global. It is beneficial to use memset if the global is all
  617. /// zeros, or mostly zeros and large.
  618. static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
  619. uint64_t GlobalSize) {
  620. // If a global is all zeros, always use a memset.
  621. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  622. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  623. // do it if it will require 6 or fewer scalar stores.
  624. // TODO: Should budget depends on the size? Avoiding a large global warrants
  625. // plopping in more stores.
  626. unsigned StoreBudget = 6;
  627. uint64_t SizeLimit = 32;
  628. return GlobalSize > SizeLimit &&
  629. canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
  630. }
  631. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  632. /// variable declaration with auto, register, or no storage class specifier.
  633. /// These turn into simple stack objects, or GlobalValues depending on target.
  634. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  635. AutoVarEmission emission = EmitAutoVarAlloca(D);
  636. EmitAutoVarInit(emission);
  637. EmitAutoVarCleanups(emission);
  638. }
  639. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  640. /// local variable. Does not emit initalization or destruction.
  641. CodeGenFunction::AutoVarEmission
  642. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  643. QualType Ty = D.getType();
  644. AutoVarEmission emission(D);
  645. bool isByRef = D.hasAttr<BlocksAttr>();
  646. emission.IsByRef = isByRef;
  647. CharUnits alignment = getContext().getDeclAlign(&D);
  648. emission.Alignment = alignment;
  649. // If the type is variably-modified, emit all the VLA sizes for it.
  650. if (Ty->isVariablyModifiedType())
  651. EmitVariablyModifiedType(Ty);
  652. llvm::Value *DeclPtr;
  653. if (Ty->isConstantSizeType()) {
  654. if (!Target.useGlobalsForAutomaticVariables()) {
  655. bool NRVO = getContext().getLangOptions().ElideConstructors &&
  656. D.isNRVOVariable();
  657. // If this value is a POD array or struct with a statically
  658. // determinable constant initializer, there are optimizations we can do.
  659. //
  660. // TODO: We should constant-evaluate the initializer of any variable,
  661. // as long as it is initialized by a constant expression. Currently,
  662. // isConstantInitializer produces wrong answers for structs with
  663. // reference or bitfield members, and a few other cases, and checking
  664. // for POD-ness protects us from some of these.
  665. if (D.getInit() &&
  666. (Ty->isArrayType() || Ty->isRecordType()) &&
  667. (Ty.isPODType(getContext()) ||
  668. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  669. D.getInit()->isConstantInitializer(getContext(), false)) {
  670. // If the variable's a const type, and it's neither an NRVO
  671. // candidate nor a __block variable and has no mutable members,
  672. // emit it as a global instead.
  673. if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  674. CGM.isTypeConstant(Ty, true)) {
  675. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  676. emission.Address = 0; // signal this condition to later callbacks
  677. assert(emission.wasEmittedAsGlobal());
  678. return emission;
  679. }
  680. // Otherwise, tell the initialization code that we're in this case.
  681. emission.IsConstantAggregate = true;
  682. }
  683. // A normal fixed sized variable becomes an alloca in the entry block,
  684. // unless it's an NRVO variable.
  685. llvm::Type *LTy = ConvertTypeForMem(Ty);
  686. if (NRVO) {
  687. // The named return value optimization: allocate this variable in the
  688. // return slot, so that we can elide the copy when returning this
  689. // variable (C++0x [class.copy]p34).
  690. DeclPtr = ReturnValue;
  691. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  692. if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
  693. // Create a flag that is used to indicate when the NRVO was applied
  694. // to this variable. Set it to zero to indicate that NRVO was not
  695. // applied.
  696. llvm::Value *Zero = Builder.getFalse();
  697. llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
  698. EnsureInsertPoint();
  699. Builder.CreateStore(Zero, NRVOFlag);
  700. // Record the NRVO flag for this variable.
  701. NRVOFlags[&D] = NRVOFlag;
  702. emission.NRVOFlag = NRVOFlag;
  703. }
  704. }
  705. } else {
  706. if (isByRef)
  707. LTy = BuildByRefType(&D);
  708. llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
  709. Alloc->setName(D.getName());
  710. CharUnits allocaAlignment = alignment;
  711. if (isByRef)
  712. allocaAlignment = std::max(allocaAlignment,
  713. getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
  714. Alloc->setAlignment(allocaAlignment.getQuantity());
  715. DeclPtr = Alloc;
  716. }
  717. } else {
  718. // Targets that don't support recursion emit locals as globals.
  719. const char *Class =
  720. D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
  721. DeclPtr = CreateStaticVarDecl(D, Class,
  722. llvm::GlobalValue::InternalLinkage);
  723. }
  724. } else {
  725. EnsureInsertPoint();
  726. if (!DidCallStackSave) {
  727. // Save the stack.
  728. llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
  729. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  730. llvm::Value *V = Builder.CreateCall(F);
  731. Builder.CreateStore(V, Stack);
  732. DidCallStackSave = true;
  733. // Push a cleanup block and restore the stack there.
  734. // FIXME: in general circumstances, this should be an EH cleanup.
  735. EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
  736. }
  737. llvm::Value *elementCount;
  738. QualType elementType;
  739. llvm::tie(elementCount, elementType) = getVLASize(Ty);
  740. llvm::Type *llvmTy = ConvertTypeForMem(elementType);
  741. // Allocate memory for the array.
  742. llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
  743. vla->setAlignment(alignment.getQuantity());
  744. DeclPtr = vla;
  745. }
  746. llvm::Value *&DMEntry = LocalDeclMap[&D];
  747. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  748. DMEntry = DeclPtr;
  749. emission.Address = DeclPtr;
  750. // Emit debug info for local var declaration.
  751. if (HaveInsertPoint())
  752. if (CGDebugInfo *DI = getDebugInfo()) {
  753. DI->setLocation(D.getLocation());
  754. if (Target.useGlobalsForAutomaticVariables()) {
  755. DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
  756. } else
  757. DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
  758. }
  759. if (D.hasAttr<AnnotateAttr>())
  760. EmitVarAnnotations(&D, emission.Address);
  761. return emission;
  762. }
  763. /// Determines whether the given __block variable is potentially
  764. /// captured by the given expression.
  765. static bool isCapturedBy(const VarDecl &var, const Expr *e) {
  766. // Skip the most common kinds of expressions that make
  767. // hierarchy-walking expensive.
  768. e = e->IgnoreParenCasts();
  769. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  770. const BlockDecl *block = be->getBlockDecl();
  771. for (BlockDecl::capture_const_iterator i = block->capture_begin(),
  772. e = block->capture_end(); i != e; ++i) {
  773. if (i->getVariable() == &var)
  774. return true;
  775. }
  776. // No need to walk into the subexpressions.
  777. return false;
  778. }
  779. if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
  780. const CompoundStmt *CS = SE->getSubStmt();
  781. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  782. BE = CS->body_end(); BI != BE; ++BI)
  783. if (Expr *E = dyn_cast<Expr>((*BI))) {
  784. if (isCapturedBy(var, E))
  785. return true;
  786. }
  787. else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
  788. // special case declarations
  789. for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
  790. I != E; ++I) {
  791. if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
  792. Expr *Init = VD->getInit();
  793. if (Init && isCapturedBy(var, Init))
  794. return true;
  795. }
  796. }
  797. }
  798. else
  799. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  800. // Later, provide code to poke into statements for capture analysis.
  801. return true;
  802. return false;
  803. }
  804. for (Stmt::const_child_range children = e->children(); children; ++children)
  805. if (isCapturedBy(var, cast<Expr>(*children)))
  806. return true;
  807. return false;
  808. }
  809. /// \brief Determine whether the given initializer is trivial in the sense
  810. /// that it requires no code to be generated.
  811. static bool isTrivialInitializer(const Expr *Init) {
  812. if (!Init)
  813. return true;
  814. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  815. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  816. if (Constructor->isTrivial() &&
  817. Constructor->isDefaultConstructor() &&
  818. !Construct->requiresZeroInitialization())
  819. return true;
  820. return false;
  821. }
  822. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  823. assert(emission.Variable && "emission was not valid!");
  824. // If this was emitted as a global constant, we're done.
  825. if (emission.wasEmittedAsGlobal()) return;
  826. const VarDecl &D = *emission.Variable;
  827. QualType type = D.getType();
  828. // If this local has an initializer, emit it now.
  829. const Expr *Init = D.getInit();
  830. // If we are at an unreachable point, we don't need to emit the initializer
  831. // unless it contains a label.
  832. if (!HaveInsertPoint()) {
  833. if (!Init || !ContainsLabel(Init)) return;
  834. EnsureInsertPoint();
  835. }
  836. // Initialize the structure of a __block variable.
  837. if (emission.IsByRef)
  838. emitByrefStructureInit(emission);
  839. if (isTrivialInitializer(Init))
  840. return;
  841. CharUnits alignment = emission.Alignment;
  842. // Check whether this is a byref variable that's potentially
  843. // captured and moved by its own initializer. If so, we'll need to
  844. // emit the initializer first, then copy into the variable.
  845. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  846. llvm::Value *Loc =
  847. capturedByInit ? emission.Address : emission.getObjectAddress(*this);
  848. llvm::Constant *constant = 0;
  849. if (emission.IsConstantAggregate) {
  850. assert(!capturedByInit && "constant init contains a capturing block?");
  851. constant = CGM.EmitConstantInit(D, this);
  852. }
  853. if (!constant) {
  854. LValue lv = MakeAddrLValue(Loc, type, alignment);
  855. lv.setNonGC(true);
  856. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  857. }
  858. // If this is a simple aggregate initialization, we can optimize it
  859. // in various ways.
  860. bool isVolatile = type.isVolatileQualified();
  861. llvm::Value *SizeVal =
  862. llvm::ConstantInt::get(IntPtrTy,
  863. getContext().getTypeSizeInChars(type).getQuantity());
  864. llvm::Type *BP = Int8PtrTy;
  865. if (Loc->getType() != BP)
  866. Loc = Builder.CreateBitCast(Loc, BP);
  867. // If the initializer is all or mostly zeros, codegen with memset then do
  868. // a few stores afterward.
  869. if (shouldUseMemSetPlusStoresToInitialize(constant,
  870. CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
  871. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  872. alignment.getQuantity(), isVolatile);
  873. if (!constant->isNullValue()) {
  874. Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
  875. emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
  876. }
  877. } else {
  878. // Otherwise, create a temporary global with the initializer then
  879. // memcpy from the global to the alloca.
  880. std::string Name = GetStaticDeclName(*this, D, ".");
  881. llvm::GlobalVariable *GV =
  882. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  883. llvm::GlobalValue::PrivateLinkage,
  884. constant, Name, 0, false, 0);
  885. GV->setAlignment(alignment.getQuantity());
  886. GV->setUnnamedAddr(true);
  887. llvm::Value *SrcPtr = GV;
  888. if (SrcPtr->getType() != BP)
  889. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  890. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
  891. isVolatile);
  892. }
  893. }
  894. /// Emit an expression as an initializer for a variable at the given
  895. /// location. The expression is not necessarily the normal
  896. /// initializer for the variable, and the address is not necessarily
  897. /// its normal location.
  898. ///
  899. /// \param init the initializing expression
  900. /// \param var the variable to act as if we're initializing
  901. /// \param loc the address to initialize; its type is a pointer
  902. /// to the LLVM mapping of the variable's type
  903. /// \param alignment the alignment of the address
  904. /// \param capturedByInit true if the variable is a __block variable
  905. /// whose address is potentially changed by the initializer
  906. void CodeGenFunction::EmitExprAsInit(const Expr *init,
  907. const ValueDecl *D,
  908. LValue lvalue,
  909. bool capturedByInit) {
  910. QualType type = D->getType();
  911. if (type->isReferenceType()) {
  912. RValue rvalue = EmitReferenceBindingToExpr(init, D);
  913. if (capturedByInit)
  914. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  915. EmitStoreThroughLValue(rvalue, lvalue, true);
  916. } else if (!hasAggregateLLVMType(type)) {
  917. EmitScalarInit(init, D, lvalue, capturedByInit);
  918. } else if (type->isAnyComplexType()) {
  919. ComplexPairTy complex = EmitComplexExpr(init);
  920. if (capturedByInit)
  921. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  922. StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
  923. } else {
  924. // TODO: how can we delay here if D is captured by its initializer?
  925. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  926. AggValueSlot::IsDestructed,
  927. AggValueSlot::DoesNotNeedGCBarriers,
  928. AggValueSlot::IsNotAliased));
  929. }
  930. }
  931. /// Enter a destroy cleanup for the given local variable.
  932. void CodeGenFunction::emitAutoVarTypeCleanup(
  933. const CodeGenFunction::AutoVarEmission &emission,
  934. QualType::DestructionKind dtorKind) {
  935. assert(dtorKind != QualType::DK_none);
  936. // Note that for __block variables, we want to destroy the
  937. // original stack object, not the possibly forwarded object.
  938. llvm::Value *addr = emission.getObjectAddress(*this);
  939. const VarDecl *var = emission.Variable;
  940. QualType type = var->getType();
  941. CleanupKind cleanupKind = NormalAndEHCleanup;
  942. CodeGenFunction::Destroyer *destroyer = 0;
  943. switch (dtorKind) {
  944. case QualType::DK_none:
  945. llvm_unreachable("no cleanup for trivially-destructible variable");
  946. case QualType::DK_cxx_destructor:
  947. // If there's an NRVO flag on the emission, we need a different
  948. // cleanup.
  949. if (emission.NRVOFlag) {
  950. assert(!type->isArrayType());
  951. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  952. EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
  953. emission.NRVOFlag);
  954. return;
  955. }
  956. break;
  957. case QualType::DK_objc_strong_lifetime:
  958. // Suppress cleanups for pseudo-strong variables.
  959. if (var->isARCPseudoStrong()) return;
  960. // Otherwise, consider whether to use an EH cleanup or not.
  961. cleanupKind = getARCCleanupKind();
  962. // Use the imprecise destroyer by default.
  963. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  964. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  965. break;
  966. case QualType::DK_objc_weak_lifetime:
  967. break;
  968. }
  969. // If we haven't chosen a more specific destroyer, use the default.
  970. if (!destroyer) destroyer = getDestroyer(dtorKind);
  971. // Use an EH cleanup in array destructors iff the destructor itself
  972. // is being pushed as an EH cleanup.
  973. bool useEHCleanup = (cleanupKind & EHCleanup);
  974. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  975. useEHCleanup);
  976. }
  977. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  978. assert(emission.Variable && "emission was not valid!");
  979. // If this was emitted as a global constant, we're done.
  980. if (emission.wasEmittedAsGlobal()) return;
  981. const VarDecl &D = *emission.Variable;
  982. // Check the type for a cleanup.
  983. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  984. emitAutoVarTypeCleanup(emission, dtorKind);
  985. // In GC mode, honor objc_precise_lifetime.
  986. if (getLangOptions().getGC() != LangOptions::NonGC &&
  987. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  988. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  989. }
  990. // Handle the cleanup attribute.
  991. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  992. const FunctionDecl *FD = CA->getFunctionDecl();
  993. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  994. assert(F && "Could not find function!");
  995. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  996. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  997. }
  998. // If this is a block variable, call _Block_object_destroy
  999. // (on the unforwarded address).
  1000. if (emission.IsByRef)
  1001. enterByrefCleanup(emission);
  1002. }
  1003. CodeGenFunction::Destroyer *
  1004. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1005. switch (kind) {
  1006. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1007. case QualType::DK_cxx_destructor:
  1008. return destroyCXXObject;
  1009. case QualType::DK_objc_strong_lifetime:
  1010. return destroyARCStrongPrecise;
  1011. case QualType::DK_objc_weak_lifetime:
  1012. return destroyARCWeak;
  1013. }
  1014. llvm_unreachable("Unknown DestructionKind");
  1015. }
  1016. /// pushDestroy - Push the standard destructor for the given type.
  1017. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1018. llvm::Value *addr, QualType type) {
  1019. assert(dtorKind && "cannot push destructor for trivial type");
  1020. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1021. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1022. cleanupKind & EHCleanup);
  1023. }
  1024. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
  1025. QualType type, Destroyer *destroyer,
  1026. bool useEHCleanupForArray) {
  1027. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1028. destroyer, useEHCleanupForArray);
  1029. }
  1030. /// emitDestroy - Immediately perform the destruction of the given
  1031. /// object.
  1032. ///
  1033. /// \param addr - the address of the object; a type*
  1034. /// \param type - the type of the object; if an array type, all
  1035. /// objects are destroyed in reverse order
  1036. /// \param destroyer - the function to call to destroy individual
  1037. /// elements
  1038. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1039. /// used when destroying array elements, in case one of the
  1040. /// destructions throws an exception
  1041. void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
  1042. Destroyer *destroyer,
  1043. bool useEHCleanupForArray) {
  1044. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1045. if (!arrayType)
  1046. return destroyer(*this, addr, type);
  1047. llvm::Value *begin = addr;
  1048. llvm::Value *length = emitArrayLength(arrayType, type, begin);
  1049. // Normally we have to check whether the array is zero-length.
  1050. bool checkZeroLength = true;
  1051. // But if the array length is constant, we can suppress that.
  1052. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1053. // ...and if it's constant zero, we can just skip the entire thing.
  1054. if (constLength->isZero()) return;
  1055. checkZeroLength = false;
  1056. }
  1057. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1058. emitArrayDestroy(begin, end, type, destroyer,
  1059. checkZeroLength, useEHCleanupForArray);
  1060. }
  1061. /// emitArrayDestroy - Destroys all the elements of the given array,
  1062. /// beginning from last to first. The array cannot be zero-length.
  1063. ///
  1064. /// \param begin - a type* denoting the first element of the array
  1065. /// \param end - a type* denoting one past the end of the array
  1066. /// \param type - the element type of the array
  1067. /// \param destroyer - the function to call to destroy elements
  1068. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1069. /// the remaining elements in case the destruction of a single
  1070. /// element throws
  1071. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1072. llvm::Value *end,
  1073. QualType type,
  1074. Destroyer *destroyer,
  1075. bool checkZeroLength,
  1076. bool useEHCleanup) {
  1077. assert(!type->isArrayType());
  1078. // The basic structure here is a do-while loop, because we don't
  1079. // need to check for the zero-element case.
  1080. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1081. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1082. if (checkZeroLength) {
  1083. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1084. "arraydestroy.isempty");
  1085. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1086. }
  1087. // Enter the loop body, making that address the current address.
  1088. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1089. EmitBlock(bodyBB);
  1090. llvm::PHINode *elementPast =
  1091. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1092. elementPast->addIncoming(end, entryBB);
  1093. // Shift the address back by one element.
  1094. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1095. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1096. "arraydestroy.element");
  1097. if (useEHCleanup)
  1098. pushRegularPartialArrayCleanup(begin, element, type, destroyer);
  1099. // Perform the actual destruction there.
  1100. destroyer(*this, element, type);
  1101. if (useEHCleanup)
  1102. PopCleanupBlock();
  1103. // Check whether we've reached the end.
  1104. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1105. Builder.CreateCondBr(done, doneBB, bodyBB);
  1106. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1107. // Done.
  1108. EmitBlock(doneBB);
  1109. }
  1110. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1111. /// emitArrayDestroy, the element type here may still be an array type.
  1112. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1113. llvm::Value *begin, llvm::Value *end,
  1114. QualType type,
  1115. CodeGenFunction::Destroyer *destroyer) {
  1116. // If the element type is itself an array, drill down.
  1117. unsigned arrayDepth = 0;
  1118. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1119. // VLAs don't require a GEP index to walk into.
  1120. if (!isa<VariableArrayType>(arrayType))
  1121. arrayDepth++;
  1122. type = arrayType->getElementType();
  1123. }
  1124. if (arrayDepth) {
  1125. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
  1126. SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
  1127. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1128. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1129. }
  1130. // Destroy the array. We don't ever need an EH cleanup because we
  1131. // assume that we're in an EH cleanup ourselves, so a throwing
  1132. // destructor causes an immediate terminate.
  1133. CGF.emitArrayDestroy(begin, end, type, destroyer,
  1134. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1135. }
  1136. namespace {
  1137. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1138. /// array destroy where the end pointer is regularly determined and
  1139. /// does not need to be loaded from a local.
  1140. class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1141. llvm::Value *ArrayBegin;
  1142. llvm::Value *ArrayEnd;
  1143. QualType ElementType;
  1144. CodeGenFunction::Destroyer *Destroyer;
  1145. public:
  1146. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1147. QualType elementType,
  1148. CodeGenFunction::Destroyer *destroyer)
  1149. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1150. ElementType(elementType), Destroyer(destroyer) {}
  1151. void Emit(CodeGenFunction &CGF, Flags flags) {
  1152. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1153. ElementType, Destroyer);
  1154. }
  1155. };
  1156. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1157. /// partial array destroy where the end pointer is irregularly
  1158. /// determined and must be loaded from a local.
  1159. class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1160. llvm::Value *ArrayBegin;
  1161. llvm::Value *ArrayEndPointer;
  1162. QualType ElementType;
  1163. CodeGenFunction::Destroyer *Destroyer;
  1164. public:
  1165. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1166. llvm::Value *arrayEndPointer,
  1167. QualType elementType,
  1168. CodeGenFunction::Destroyer *destroyer)
  1169. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1170. ElementType(elementType), Destroyer(destroyer) {}
  1171. void Emit(CodeGenFunction &CGF, Flags flags) {
  1172. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1173. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1174. ElementType, Destroyer);
  1175. }
  1176. };
  1177. }
  1178. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1179. /// already-constructed elements of the given array. The cleanup
  1180. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1181. ///
  1182. /// \param elementType - the immediate element type of the array;
  1183. /// possibly still an array type
  1184. /// \param array - a value of type elementType*
  1185. /// \param destructionKind - the kind of destruction required
  1186. /// \param initializedElementCount - a value of type size_t* holding
  1187. /// the number of successfully-constructed elements
  1188. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1189. llvm::Value *arrayEndPointer,
  1190. QualType elementType,
  1191. Destroyer *destroyer) {
  1192. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1193. arrayBegin, arrayEndPointer,
  1194. elementType, destroyer);
  1195. }
  1196. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1197. /// already-constructed elements of the given array. The cleanup
  1198. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1199. ///
  1200. /// \param elementType - the immediate element type of the array;
  1201. /// possibly still an array type
  1202. /// \param array - a value of type elementType*
  1203. /// \param destructionKind - the kind of destruction required
  1204. /// \param initializedElementCount - a value of type size_t* holding
  1205. /// the number of successfully-constructed elements
  1206. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1207. llvm::Value *arrayEnd,
  1208. QualType elementType,
  1209. Destroyer *destroyer) {
  1210. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1211. arrayBegin, arrayEnd,
  1212. elementType, destroyer);
  1213. }
  1214. namespace {
  1215. /// A cleanup to perform a release of an object at the end of a
  1216. /// function. This is used to balance out the incoming +1 of a
  1217. /// ns_consumed argument when we can't reasonably do that just by
  1218. /// not doing the initial retain for a __block argument.
  1219. struct ConsumeARCParameter : EHScopeStack::Cleanup {
  1220. ConsumeARCParameter(llvm::Value *param) : Param(param) {}
  1221. llvm::Value *Param;
  1222. void Emit(CodeGenFunction &CGF, Flags flags) {
  1223. CGF.EmitARCRelease(Param, /*precise*/ false);
  1224. }
  1225. };
  1226. }
  1227. /// Emit an alloca (or GlobalValue depending on target)
  1228. /// for the specified parameter and set up LocalDeclMap.
  1229. void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
  1230. unsigned ArgNo) {
  1231. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1232. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1233. "Invalid argument to EmitParmDecl");
  1234. Arg->setName(D.getName());
  1235. // Use better IR generation for certain implicit parameters.
  1236. if (isa<ImplicitParamDecl>(D)) {
  1237. // The only implicit argument a block has is its literal.
  1238. if (BlockInfo) {
  1239. LocalDeclMap[&D] = Arg;
  1240. if (CGDebugInfo *DI = getDebugInfo()) {
  1241. DI->setLocation(D.getLocation());
  1242. DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
  1243. }
  1244. return;
  1245. }
  1246. }
  1247. QualType Ty = D.getType();
  1248. llvm::Value *DeclPtr;
  1249. // If this is an aggregate or variable sized value, reuse the input pointer.
  1250. if (!Ty->isConstantSizeType() ||
  1251. CodeGenFunction::hasAggregateLLVMType(Ty)) {
  1252. DeclPtr = Arg;
  1253. } else {
  1254. // Otherwise, create a temporary to hold the value.
  1255. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
  1256. D.getName() + ".addr");
  1257. Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  1258. DeclPtr = Alloc;
  1259. bool doStore = true;
  1260. Qualifiers qs = Ty.getQualifiers();
  1261. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1262. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1263. // For __strong, it's handled by just skipping the initial retain;
  1264. // otherwise we have to balance out the initial +1 with an extra
  1265. // cleanup to do the release at the end of the function.
  1266. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1267. // 'self' is always formally __strong, but if this is not an
  1268. // init method then we don't want to retain it.
  1269. if (D.isARCPseudoStrong()) {
  1270. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1271. assert(&D == method->getSelfDecl());
  1272. assert(lt == Qualifiers::OCL_Strong);
  1273. assert(qs.hasConst());
  1274. assert(method->getMethodFamily() != OMF_init);
  1275. (void) method;
  1276. lt = Qualifiers::OCL_ExplicitNone;
  1277. }
  1278. if (lt == Qualifiers::OCL_Strong) {
  1279. if (!isConsumed)
  1280. // Don't use objc_retainBlock for block pointers, because we
  1281. // don't want to Block_copy something just because we got it
  1282. // as a parameter.
  1283. Arg = EmitARCRetainNonBlock(Arg);
  1284. } else {
  1285. // Push the cleanup for a consumed parameter.
  1286. if (isConsumed)
  1287. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
  1288. if (lt == Qualifiers::OCL_Weak) {
  1289. EmitARCInitWeak(DeclPtr, Arg);
  1290. doStore = false; // The weak init is a store, no need to do two
  1291. }
  1292. }
  1293. // Enter the cleanup scope.
  1294. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1295. }
  1296. // Store the initial value into the alloca.
  1297. if (doStore) {
  1298. LValue lv = MakeAddrLValue(DeclPtr, Ty,
  1299. getContext().getDeclAlign(&D));
  1300. EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
  1301. }
  1302. }
  1303. llvm::Value *&DMEntry = LocalDeclMap[&D];
  1304. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  1305. DMEntry = DeclPtr;
  1306. // Emit debug info for param declaration.
  1307. if (CGDebugInfo *DI = getDebugInfo())
  1308. DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
  1309. if (D.hasAttr<AnnotateAttr>())
  1310. EmitVarAnnotations(&D, DeclPtr);
  1311. }