CGDecl.cpp 57 KB

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