CodeGenModule.cpp 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  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 coordinates the per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCall.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGObjCRuntime.h"
  19. #include "CGOpenCLRuntime.h"
  20. #include "CodeGenFunction.h"
  21. #include "CodeGenTBAA.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/CharUnits.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/DeclTemplate.h"
  28. #include "clang/AST/Mangle.h"
  29. #include "clang/AST/RecordLayout.h"
  30. #include "clang/AST/RecursiveASTVisitor.h"
  31. #include "clang/Basic/Builtins.h"
  32. #include "clang/Basic/CharInfo.h"
  33. #include "clang/Basic/Diagnostic.h"
  34. #include "clang/Basic/Module.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. #include "clang/Basic/Version.h"
  38. #include "clang/Frontend/CodeGenOptions.h"
  39. #include "llvm/ADT/APSInt.h"
  40. #include "llvm/ADT/Triple.h"
  41. #include "llvm/IR/CallingConv.h"
  42. #include "llvm/IR/DataLayout.h"
  43. #include "llvm/IR/Intrinsics.h"
  44. #include "llvm/IR/LLVMContext.h"
  45. #include "llvm/IR/Module.h"
  46. #include "llvm/Support/CallSite.h"
  47. #include "llvm/Support/ConvertUTF.h"
  48. #include "llvm/Support/ErrorHandling.h"
  49. #include "llvm/Target/Mangler.h"
  50. using namespace clang;
  51. using namespace CodeGen;
  52. static const char AnnotationSection[] = "llvm.metadata";
  53. static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
  54. switch (CGM.getTarget().getCXXABI().getKind()) {
  55. case TargetCXXABI::GenericAArch64:
  56. case TargetCXXABI::GenericARM:
  57. case TargetCXXABI::iOS:
  58. case TargetCXXABI::GenericItanium:
  59. return *CreateItaniumCXXABI(CGM);
  60. case TargetCXXABI::Microsoft:
  61. return *CreateMicrosoftCXXABI(CGM);
  62. }
  63. llvm_unreachable("invalid C++ ABI kind");
  64. }
  65. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  66. llvm::Module &M, const llvm::DataLayout &TD,
  67. DiagnosticsEngine &diags)
  68. : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
  69. Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
  70. ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
  71. TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0),
  72. OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0),
  73. NoObjCARCExceptionsMetadata(0), RRData(0), CFConstantStringClassRef(0),
  74. ConstantStringClassRef(0), NSConstantStringType(0),
  75. NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0),
  76. BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0),
  77. LifetimeStartFn(0), LifetimeEndFn(0),
  78. SanitizerBlacklist(
  79. llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
  80. SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
  81. : LangOpts.Sanitize) {
  82. // Initialize the type cache.
  83. llvm::LLVMContext &LLVMContext = M.getContext();
  84. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  85. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  86. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  87. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  88. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  89. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  90. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  91. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  92. PointerAlignInBytes =
  93. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  94. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  95. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  96. Int8PtrTy = Int8Ty->getPointerTo(0);
  97. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  98. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  99. if (LangOpts.ObjC1)
  100. createObjCRuntime();
  101. if (LangOpts.OpenCL)
  102. createOpenCLRuntime();
  103. if (LangOpts.CUDA)
  104. createCUDARuntime();
  105. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  106. if (SanOpts.Thread ||
  107. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  108. TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  109. ABI.getMangleContext());
  110. // If debug info or coverage generation is enabled, create the CGDebugInfo
  111. // object.
  112. if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
  113. CodeGenOpts.EmitGcovArcs ||
  114. CodeGenOpts.EmitGcovNotes)
  115. DebugInfo = new CGDebugInfo(*this);
  116. Block.GlobalUniqueCount = 0;
  117. if (C.getLangOpts().ObjCAutoRefCount)
  118. ARCData = new ARCEntrypoints();
  119. RRData = new RREntrypoints();
  120. }
  121. CodeGenModule::~CodeGenModule() {
  122. delete ObjCRuntime;
  123. delete OpenCLRuntime;
  124. delete CUDARuntime;
  125. delete TheTargetCodeGenInfo;
  126. delete &ABI;
  127. delete TBAA;
  128. delete DebugInfo;
  129. delete ARCData;
  130. delete RRData;
  131. }
  132. void CodeGenModule::createObjCRuntime() {
  133. // This is just isGNUFamily(), but we want to force implementors of
  134. // new ABIs to decide how best to do this.
  135. switch (LangOpts.ObjCRuntime.getKind()) {
  136. case ObjCRuntime::GNUstep:
  137. case ObjCRuntime::GCC:
  138. case ObjCRuntime::ObjFW:
  139. ObjCRuntime = CreateGNUObjCRuntime(*this);
  140. return;
  141. case ObjCRuntime::FragileMacOSX:
  142. case ObjCRuntime::MacOSX:
  143. case ObjCRuntime::iOS:
  144. ObjCRuntime = CreateMacObjCRuntime(*this);
  145. return;
  146. }
  147. llvm_unreachable("bad runtime kind");
  148. }
  149. void CodeGenModule::createOpenCLRuntime() {
  150. OpenCLRuntime = new CGOpenCLRuntime(*this);
  151. }
  152. void CodeGenModule::createCUDARuntime() {
  153. CUDARuntime = CreateNVCUDARuntime(*this);
  154. }
  155. void CodeGenModule::Release() {
  156. EmitDeferred();
  157. EmitCXXGlobalInitFunc();
  158. EmitCXXGlobalDtorFunc();
  159. EmitCXXThreadLocalInitFunc();
  160. if (ObjCRuntime)
  161. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  162. AddGlobalCtor(ObjCInitFunction);
  163. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  164. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  165. EmitGlobalAnnotations();
  166. EmitStaticExternCAliases();
  167. EmitLLVMUsed();
  168. if (CodeGenOpts.Autolink &&
  169. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  170. EmitModuleLinkOptions();
  171. }
  172. if (CodeGenOpts.DwarfVersion)
  173. // We actually want the latest version when there are conflicts.
  174. // We can change from Warning to Latest if such mode is supported.
  175. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  176. CodeGenOpts.DwarfVersion);
  177. SimplifyPersonality();
  178. if (getCodeGenOpts().EmitDeclMetadata)
  179. EmitDeclMetadata();
  180. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  181. EmitCoverageFile();
  182. if (DebugInfo)
  183. DebugInfo->finalize();
  184. EmitVersionIdentMetadata();
  185. }
  186. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  187. // Make sure that this type is translated.
  188. Types.UpdateCompletedType(TD);
  189. }
  190. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  191. if (!TBAA)
  192. return 0;
  193. return TBAA->getTBAAInfo(QTy);
  194. }
  195. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  196. if (!TBAA)
  197. return 0;
  198. return TBAA->getTBAAInfoForVTablePtr();
  199. }
  200. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  201. if (!TBAA)
  202. return 0;
  203. return TBAA->getTBAAStructInfo(QTy);
  204. }
  205. llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
  206. if (!TBAA)
  207. return 0;
  208. return TBAA->getTBAAStructTypeInfo(QTy);
  209. }
  210. llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
  211. llvm::MDNode *AccessN,
  212. uint64_t O) {
  213. if (!TBAA)
  214. return 0;
  215. return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
  216. }
  217. /// Decorate the instruction with a TBAA tag. For both scalar TBAA
  218. /// and struct-path aware TBAA, the tag has the same format:
  219. /// base type, access type and offset.
  220. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  221. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  222. llvm::MDNode *TBAAInfo,
  223. bool ConvertTypeToTag) {
  224. if (ConvertTypeToTag && TBAA)
  225. Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
  226. TBAA->getTBAAScalarTagInfo(TBAAInfo));
  227. else
  228. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  229. }
  230. void CodeGenModule::Error(SourceLocation loc, StringRef error) {
  231. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
  232. getDiags().Report(Context.getFullLoc(loc), diagID);
  233. }
  234. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  235. /// specified stmt yet.
  236. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  237. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  238. "cannot compile this %0 yet");
  239. std::string Msg = Type;
  240. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  241. << Msg << S->getSourceRange();
  242. }
  243. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  244. /// specified decl yet.
  245. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  246. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  247. "cannot compile this %0 yet");
  248. std::string Msg = Type;
  249. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  250. }
  251. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  252. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  253. }
  254. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  255. const NamedDecl *D) const {
  256. // Internal definitions always have default visibility.
  257. if (GV->hasLocalLinkage()) {
  258. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  259. return;
  260. }
  261. // Set visibility for definitions.
  262. LinkageInfo LV = D->getLinkageAndVisibility();
  263. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  264. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  265. }
  266. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  267. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  268. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  269. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  270. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  271. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  272. }
  273. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  274. CodeGenOptions::TLSModel M) {
  275. switch (M) {
  276. case CodeGenOptions::GeneralDynamicTLSModel:
  277. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  278. case CodeGenOptions::LocalDynamicTLSModel:
  279. return llvm::GlobalVariable::LocalDynamicTLSModel;
  280. case CodeGenOptions::InitialExecTLSModel:
  281. return llvm::GlobalVariable::InitialExecTLSModel;
  282. case CodeGenOptions::LocalExecTLSModel:
  283. return llvm::GlobalVariable::LocalExecTLSModel;
  284. }
  285. llvm_unreachable("Invalid TLS model!");
  286. }
  287. void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
  288. const VarDecl &D) const {
  289. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  290. llvm::GlobalVariable::ThreadLocalMode TLM;
  291. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  292. // Override the TLS model if it is explicitly specified.
  293. if (D.hasAttr<TLSModelAttr>()) {
  294. const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
  295. TLM = GetLLVMTLSModel(Attr->getModel());
  296. }
  297. GV->setThreadLocalMode(TLM);
  298. }
  299. /// Set the symbol visibility of type information (vtable and RTTI)
  300. /// associated with the given type.
  301. void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
  302. const CXXRecordDecl *RD,
  303. TypeVisibilityKind TVK) const {
  304. setGlobalVisibility(GV, RD);
  305. if (!CodeGenOpts.HiddenWeakVTables)
  306. return;
  307. // We never want to drop the visibility for RTTI names.
  308. if (TVK == TVK_ForRTTIName)
  309. return;
  310. // We want to drop the visibility to hidden for weak type symbols.
  311. // This isn't possible if there might be unresolved references
  312. // elsewhere that rely on this symbol being visible.
  313. // This should be kept roughly in sync with setThunkVisibility
  314. // in CGVTables.cpp.
  315. // Preconditions.
  316. if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
  317. GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  318. return;
  319. // Don't override an explicit visibility attribute.
  320. if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
  321. return;
  322. switch (RD->getTemplateSpecializationKind()) {
  323. // We have to disable the optimization if this is an EI definition
  324. // because there might be EI declarations in other shared objects.
  325. case TSK_ExplicitInstantiationDefinition:
  326. case TSK_ExplicitInstantiationDeclaration:
  327. return;
  328. // Every use of a non-template class's type information has to emit it.
  329. case TSK_Undeclared:
  330. break;
  331. // In theory, implicit instantiations can ignore the possibility of
  332. // an explicit instantiation declaration because there necessarily
  333. // must be an EI definition somewhere with default visibility. In
  334. // practice, it's possible to have an explicit instantiation for
  335. // an arbitrary template class, and linkers aren't necessarily able
  336. // to deal with mixed-visibility symbols.
  337. case TSK_ExplicitSpecialization:
  338. case TSK_ImplicitInstantiation:
  339. return;
  340. }
  341. // If there's a key function, there may be translation units
  342. // that don't have the key function's definition. But ignore
  343. // this if we're emitting RTTI under -fno-rtti.
  344. if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
  345. // FIXME: what should we do if we "lose" the key function during
  346. // the emission of the file?
  347. if (Context.getCurrentKeyFunction(RD))
  348. return;
  349. }
  350. // Otherwise, drop the visibility to hidden.
  351. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  352. GV->setUnnamedAddr(true);
  353. }
  354. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  355. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  356. StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
  357. if (!Str.empty())
  358. return Str;
  359. if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  360. IdentifierInfo *II = ND->getIdentifier();
  361. assert(II && "Attempt to mangle unnamed decl.");
  362. Str = II->getName();
  363. return Str;
  364. }
  365. SmallString<256> Buffer;
  366. llvm::raw_svector_ostream Out(Buffer);
  367. if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
  368. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  369. else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
  370. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  371. else
  372. getCXXABI().getMangleContext().mangleName(ND, Out);
  373. // Allocate space for the mangled name.
  374. Out.flush();
  375. size_t Length = Buffer.size();
  376. char *Name = MangledNamesAllocator.Allocate<char>(Length);
  377. std::copy(Buffer.begin(), Buffer.end(), Name);
  378. Str = StringRef(Name, Length);
  379. return Str;
  380. }
  381. void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
  382. const BlockDecl *BD) {
  383. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  384. const Decl *D = GD.getDecl();
  385. llvm::raw_svector_ostream Out(Buffer.getBuffer());
  386. if (D == 0)
  387. MangleCtx.mangleGlobalBlock(BD,
  388. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  389. else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  390. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  391. else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
  392. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  393. else
  394. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  395. }
  396. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  397. return getModule().getNamedValue(Name);
  398. }
  399. /// AddGlobalCtor - Add a function to the list that will be called before
  400. /// main() runs.
  401. void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
  402. // FIXME: Type coercion of void()* types.
  403. GlobalCtors.push_back(std::make_pair(Ctor, Priority));
  404. }
  405. /// AddGlobalDtor - Add a function to the list that will be called
  406. /// when the module is unloaded.
  407. void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
  408. // FIXME: Type coercion of void()* types.
  409. GlobalDtors.push_back(std::make_pair(Dtor, Priority));
  410. }
  411. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  412. // Ctor function type is void()*.
  413. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  414. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  415. // Get the type of a ctor entry, { i32, void ()* }.
  416. llvm::StructType *CtorStructTy =
  417. llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
  418. // Construct the constructor and destructor arrays.
  419. SmallVector<llvm::Constant*, 8> Ctors;
  420. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  421. llvm::Constant *S[] = {
  422. llvm::ConstantInt::get(Int32Ty, I->second, false),
  423. llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
  424. };
  425. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  426. }
  427. if (!Ctors.empty()) {
  428. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  429. new llvm::GlobalVariable(TheModule, AT, false,
  430. llvm::GlobalValue::AppendingLinkage,
  431. llvm::ConstantArray::get(AT, Ctors),
  432. GlobalName);
  433. }
  434. }
  435. llvm::GlobalValue::LinkageTypes
  436. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  437. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  438. if (isa<CXXDestructorDecl>(D) &&
  439. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  440. GD.getDtorType()))
  441. return llvm::Function::LinkOnceODRLinkage;
  442. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  443. if (Linkage == GVA_Internal)
  444. return llvm::Function::InternalLinkage;
  445. if (D->hasAttr<DLLExportAttr>())
  446. return llvm::Function::DLLExportLinkage;
  447. if (D->hasAttr<WeakAttr>())
  448. return llvm::Function::WeakAnyLinkage;
  449. // In C99 mode, 'inline' functions are guaranteed to have a strong
  450. // definition somewhere else, so we can use available_externally linkage.
  451. if (Linkage == GVA_C99Inline)
  452. return llvm::Function::AvailableExternallyLinkage;
  453. // Note that Apple's kernel linker doesn't support symbol
  454. // coalescing, so we need to avoid linkonce and weak linkages there.
  455. // Normally, this means we just map to internal, but for explicit
  456. // instantiations we'll map to external.
  457. // In C++, the compiler has to emit a definition in every translation unit
  458. // that references the function. We should use linkonce_odr because
  459. // a) if all references in this translation unit are optimized away, we
  460. // don't need to codegen it. b) if the function persists, it needs to be
  461. // merged with other definitions. c) C++ has the ODR, so we know the
  462. // definition is dependable.
  463. if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
  464. return !Context.getLangOpts().AppleKext
  465. ? llvm::Function::LinkOnceODRLinkage
  466. : llvm::Function::InternalLinkage;
  467. // An explicit instantiation of a template has weak linkage, since
  468. // explicit instantiations can occur in multiple translation units
  469. // and must all be equivalent. However, we are not allowed to
  470. // throw away these explicit instantiations.
  471. if (Linkage == GVA_ExplicitTemplateInstantiation)
  472. return !Context.getLangOpts().AppleKext
  473. ? llvm::Function::WeakODRLinkage
  474. : llvm::Function::ExternalLinkage;
  475. // Otherwise, we have strong external linkage.
  476. assert(Linkage == GVA_StrongExternal);
  477. return llvm::Function::ExternalLinkage;
  478. }
  479. /// SetFunctionDefinitionAttributes - Set attributes for a global.
  480. ///
  481. /// FIXME: This is currently only done for aliases and functions, but not for
  482. /// variables (these details are set in EmitGlobalVarDefinition for variables).
  483. void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
  484. llvm::GlobalValue *GV) {
  485. SetCommonAttributes(D, GV);
  486. }
  487. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  488. const CGFunctionInfo &Info,
  489. llvm::Function *F) {
  490. unsigned CallingConv;
  491. AttributeListType AttributeList;
  492. ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
  493. F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
  494. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  495. }
  496. /// Determines whether the language options require us to model
  497. /// unwind exceptions. We treat -fexceptions as mandating this
  498. /// except under the fragile ObjC ABI with only ObjC exceptions
  499. /// enabled. This means, for example, that C with -fexceptions
  500. /// enables this.
  501. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  502. // If exceptions are completely disabled, obviously this is false.
  503. if (!LangOpts.Exceptions) return false;
  504. // If C++ exceptions are enabled, this is true.
  505. if (LangOpts.CXXExceptions) return true;
  506. // If ObjC exceptions are enabled, this depends on the ABI.
  507. if (LangOpts.ObjCExceptions) {
  508. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  509. }
  510. return true;
  511. }
  512. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  513. llvm::Function *F) {
  514. llvm::AttrBuilder B;
  515. if (CodeGenOpts.UnwindTables)
  516. B.addAttribute(llvm::Attribute::UWTable);
  517. if (!hasUnwindExceptions(LangOpts))
  518. B.addAttribute(llvm::Attribute::NoUnwind);
  519. if (D->hasAttr<NakedAttr>()) {
  520. // Naked implies noinline: we should not be inlining such functions.
  521. B.addAttribute(llvm::Attribute::Naked);
  522. B.addAttribute(llvm::Attribute::NoInline);
  523. } else if (D->hasAttr<NoInlineAttr>()) {
  524. B.addAttribute(llvm::Attribute::NoInline);
  525. } else if ((D->hasAttr<AlwaysInlineAttr>() ||
  526. D->hasAttr<ForceInlineAttr>()) &&
  527. !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
  528. llvm::Attribute::NoInline)) {
  529. // (noinline wins over always_inline, and we can't specify both in IR)
  530. B.addAttribute(llvm::Attribute::AlwaysInline);
  531. }
  532. if (D->hasAttr<ColdAttr>()) {
  533. B.addAttribute(llvm::Attribute::OptimizeForSize);
  534. B.addAttribute(llvm::Attribute::Cold);
  535. }
  536. if (D->hasAttr<MinSizeAttr>())
  537. B.addAttribute(llvm::Attribute::MinSize);
  538. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  539. B.addAttribute(llvm::Attribute::StackProtect);
  540. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  541. B.addAttribute(llvm::Attribute::StackProtectReq);
  542. // Add sanitizer attributes if function is not blacklisted.
  543. if (!SanitizerBlacklist->isIn(*F)) {
  544. // When AddressSanitizer is enabled, set SanitizeAddress attribute
  545. // unless __attribute__((no_sanitize_address)) is used.
  546. if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
  547. B.addAttribute(llvm::Attribute::SanitizeAddress);
  548. // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
  549. if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
  550. B.addAttribute(llvm::Attribute::SanitizeThread);
  551. }
  552. // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
  553. if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
  554. B.addAttribute(llvm::Attribute::SanitizeMemory);
  555. }
  556. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  557. llvm::AttributeSet::get(
  558. F->getContext(), llvm::AttributeSet::FunctionIndex, B));
  559. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  560. F->setUnnamedAddr(true);
  561. else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
  562. if (MD->isVirtual())
  563. F->setUnnamedAddr(true);
  564. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  565. if (alignment)
  566. F->setAlignment(alignment);
  567. // C++ ABI requires 2-byte alignment for member functions.
  568. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  569. F->setAlignment(2);
  570. }
  571. void CodeGenModule::SetCommonAttributes(const Decl *D,
  572. llvm::GlobalValue *GV) {
  573. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  574. setGlobalVisibility(GV, ND);
  575. else
  576. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  577. if (D->hasAttr<UsedAttr>())
  578. AddUsedGlobal(GV);
  579. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  580. GV->setSection(SA->getName());
  581. // Alias cannot have attributes. Filter them here.
  582. if (!isa<llvm::GlobalAlias>(GV))
  583. getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
  584. }
  585. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  586. llvm::Function *F,
  587. const CGFunctionInfo &FI) {
  588. SetLLVMFunctionAttributes(D, FI, F);
  589. SetLLVMFunctionAttributesForDefinition(D, F);
  590. F->setLinkage(llvm::Function::InternalLinkage);
  591. SetCommonAttributes(D, F);
  592. }
  593. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
  594. llvm::Function *F,
  595. bool IsIncompleteFunction) {
  596. if (unsigned IID = F->getIntrinsicID()) {
  597. // If this is an intrinsic function, set the function's attributes
  598. // to the intrinsic's attributes.
  599. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
  600. (llvm::Intrinsic::ID)IID));
  601. return;
  602. }
  603. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  604. if (!IsIncompleteFunction)
  605. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  606. if (getCXXABI().HasThisReturn(GD)) {
  607. assert(!F->arg_empty() &&
  608. F->arg_begin()->getType()
  609. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  610. "unexpected this return");
  611. F->addAttribute(1, llvm::Attribute::Returned);
  612. }
  613. // Only a few attributes are set on declarations; these may later be
  614. // overridden by a definition.
  615. if (FD->hasAttr<DLLImportAttr>()) {
  616. F->setLinkage(llvm::Function::DLLImportLinkage);
  617. } else if (FD->hasAttr<WeakAttr>() ||
  618. FD->isWeakImported()) {
  619. // "extern_weak" is overloaded in LLVM; we probably should have
  620. // separate linkage types for this.
  621. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  622. } else {
  623. F->setLinkage(llvm::Function::ExternalLinkage);
  624. LinkageInfo LV = FD->getLinkageAndVisibility();
  625. if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
  626. F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  627. }
  628. }
  629. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  630. F->setSection(SA->getName());
  631. // A replaceable global allocation function does not act like a builtin by
  632. // default, only if it is invoked by a new-expression or delete-expression.
  633. if (FD->isReplaceableGlobalAllocationFunction())
  634. F->addAttribute(llvm::AttributeSet::FunctionIndex,
  635. llvm::Attribute::NoBuiltin);
  636. }
  637. void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
  638. assert(!GV->isDeclaration() &&
  639. "Only globals with definition can force usage.");
  640. LLVMUsed.push_back(GV);
  641. }
  642. void CodeGenModule::EmitLLVMUsed() {
  643. // Don't create llvm.used if there is no need.
  644. if (LLVMUsed.empty())
  645. return;
  646. // Convert LLVMUsed to what ConstantArray needs.
  647. SmallVector<llvm::Constant*, 8> UsedArray;
  648. UsedArray.resize(LLVMUsed.size());
  649. for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
  650. UsedArray[i] =
  651. llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
  652. Int8PtrTy);
  653. }
  654. if (UsedArray.empty())
  655. return;
  656. llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
  657. llvm::GlobalVariable *GV =
  658. new llvm::GlobalVariable(getModule(), ATy, false,
  659. llvm::GlobalValue::AppendingLinkage,
  660. llvm::ConstantArray::get(ATy, UsedArray),
  661. "llvm.used");
  662. GV->setSection("llvm.metadata");
  663. }
  664. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  665. llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  666. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  667. }
  668. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  669. llvm::SmallString<32> Opt;
  670. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  671. llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  672. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  673. }
  674. void CodeGenModule::AddDependentLib(StringRef Lib) {
  675. llvm::SmallString<24> Opt;
  676. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  677. llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  678. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  679. }
  680. /// \brief Add link options implied by the given module, including modules
  681. /// it depends on, using a postorder walk.
  682. static void addLinkOptionsPostorder(CodeGenModule &CGM,
  683. Module *Mod,
  684. SmallVectorImpl<llvm::Value *> &Metadata,
  685. llvm::SmallPtrSet<Module *, 16> &Visited) {
  686. // Import this module's parent.
  687. if (Mod->Parent && Visited.insert(Mod->Parent)) {
  688. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  689. }
  690. // Import this module's dependencies.
  691. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  692. if (Visited.insert(Mod->Imports[I-1]))
  693. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  694. }
  695. // Add linker options to link against the libraries/frameworks
  696. // described by this module.
  697. llvm::LLVMContext &Context = CGM.getLLVMContext();
  698. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  699. // Link against a framework. Frameworks are currently Darwin only, so we
  700. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  701. if (Mod->LinkLibraries[I-1].IsFramework) {
  702. llvm::Value *Args[2] = {
  703. llvm::MDString::get(Context, "-framework"),
  704. llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
  705. };
  706. Metadata.push_back(llvm::MDNode::get(Context, Args));
  707. continue;
  708. }
  709. // Link against a library.
  710. llvm::SmallString<24> Opt;
  711. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  712. Mod->LinkLibraries[I-1].Library, Opt);
  713. llvm::Value *OptString = llvm::MDString::get(Context, Opt);
  714. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  715. }
  716. }
  717. void CodeGenModule::EmitModuleLinkOptions() {
  718. // Collect the set of all of the modules we want to visit to emit link
  719. // options, which is essentially the imported modules and all of their
  720. // non-explicit child modules.
  721. llvm::SetVector<clang::Module *> LinkModules;
  722. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  723. SmallVector<clang::Module *, 16> Stack;
  724. // Seed the stack with imported modules.
  725. for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
  726. MEnd = ImportedModules.end();
  727. M != MEnd; ++M) {
  728. if (Visited.insert(*M))
  729. Stack.push_back(*M);
  730. }
  731. // Find all of the modules to import, making a little effort to prune
  732. // non-leaf modules.
  733. while (!Stack.empty()) {
  734. clang::Module *Mod = Stack.pop_back_val();
  735. bool AnyChildren = false;
  736. // Visit the submodules of this module.
  737. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  738. SubEnd = Mod->submodule_end();
  739. Sub != SubEnd; ++Sub) {
  740. // Skip explicit children; they need to be explicitly imported to be
  741. // linked against.
  742. if ((*Sub)->IsExplicit)
  743. continue;
  744. if (Visited.insert(*Sub)) {
  745. Stack.push_back(*Sub);
  746. AnyChildren = true;
  747. }
  748. }
  749. // We didn't find any children, so add this module to the list of
  750. // modules to link against.
  751. if (!AnyChildren) {
  752. LinkModules.insert(Mod);
  753. }
  754. }
  755. // Add link options for all of the imported modules in reverse topological
  756. // order. We don't do anything to try to order import link flags with respect
  757. // to linker options inserted by things like #pragma comment().
  758. SmallVector<llvm::Value *, 16> MetadataArgs;
  759. Visited.clear();
  760. for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
  761. MEnd = LinkModules.end();
  762. M != MEnd; ++M) {
  763. if (Visited.insert(*M))
  764. addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
  765. }
  766. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  767. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  768. // Add the linker options metadata flag.
  769. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  770. llvm::MDNode::get(getLLVMContext(),
  771. LinkerOptionsMetadata));
  772. }
  773. void CodeGenModule::EmitDeferred() {
  774. // Emit code for any potentially referenced deferred decls. Since a
  775. // previously unused static decl may become used during the generation of code
  776. // for a static function, iterate until no changes are made.
  777. while (true) {
  778. if (!DeferredVTables.empty()) {
  779. EmitDeferredVTables();
  780. // Emitting a v-table doesn't directly cause more v-tables to
  781. // become deferred, although it can cause functions to be
  782. // emitted that then need those v-tables.
  783. assert(DeferredVTables.empty());
  784. }
  785. // Stop if we're out of both deferred v-tables and deferred declarations.
  786. if (DeferredDeclsToEmit.empty()) break;
  787. GlobalDecl D = DeferredDeclsToEmit.back();
  788. DeferredDeclsToEmit.pop_back();
  789. // Check to see if we've already emitted this. This is necessary
  790. // for a couple of reasons: first, decls can end up in the
  791. // deferred-decls queue multiple times, and second, decls can end
  792. // up with definitions in unusual ways (e.g. by an extern inline
  793. // function acquiring a strong function redefinition). Just
  794. // ignore these cases.
  795. //
  796. // TODO: That said, looking this up multiple times is very wasteful.
  797. StringRef Name = getMangledName(D);
  798. llvm::GlobalValue *CGRef = GetGlobalValue(Name);
  799. assert(CGRef && "Deferred decl wasn't referenced?");
  800. if (!CGRef->isDeclaration())
  801. continue;
  802. // GlobalAlias::isDeclaration() defers to the aliasee, but for our
  803. // purposes an alias counts as a definition.
  804. if (isa<llvm::GlobalAlias>(CGRef))
  805. continue;
  806. // Otherwise, emit the definition and move on to the next one.
  807. EmitGlobalDefinition(D);
  808. }
  809. }
  810. void CodeGenModule::EmitGlobalAnnotations() {
  811. if (Annotations.empty())
  812. return;
  813. // Create a new global variable for the ConstantStruct in the Module.
  814. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  815. Annotations[0]->getType(), Annotations.size()), Annotations);
  816. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
  817. Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
  818. "llvm.global.annotations");
  819. gv->setSection(AnnotationSection);
  820. }
  821. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  822. llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
  823. if (i != AnnotationStrings.end())
  824. return i->second;
  825. // Not found yet, create a new global.
  826. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  827. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
  828. true, llvm::GlobalValue::PrivateLinkage, s, ".str");
  829. gv->setSection(AnnotationSection);
  830. gv->setUnnamedAddr(true);
  831. AnnotationStrings[Str] = gv;
  832. return gv;
  833. }
  834. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  835. SourceManager &SM = getContext().getSourceManager();
  836. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  837. if (PLoc.isValid())
  838. return EmitAnnotationString(PLoc.getFilename());
  839. return EmitAnnotationString(SM.getBufferName(Loc));
  840. }
  841. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  842. SourceManager &SM = getContext().getSourceManager();
  843. PresumedLoc PLoc = SM.getPresumedLoc(L);
  844. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  845. SM.getExpansionLineNumber(L);
  846. return llvm::ConstantInt::get(Int32Ty, LineNo);
  847. }
  848. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  849. const AnnotateAttr *AA,
  850. SourceLocation L) {
  851. // Get the globals for file name, annotation, and the line number.
  852. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  853. *UnitGV = EmitAnnotationUnit(L),
  854. *LineNoCst = EmitAnnotationLineNo(L);
  855. // Create the ConstantStruct for the global annotation.
  856. llvm::Constant *Fields[4] = {
  857. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  858. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  859. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  860. LineNoCst
  861. };
  862. return llvm::ConstantStruct::getAnon(Fields);
  863. }
  864. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  865. llvm::GlobalValue *GV) {
  866. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  867. // Get the struct elements for these annotations.
  868. for (specific_attr_iterator<AnnotateAttr>
  869. ai = D->specific_attr_begin<AnnotateAttr>(),
  870. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  871. Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
  872. }
  873. bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
  874. // Never defer when EmitAllDecls is specified.
  875. if (LangOpts.EmitAllDecls)
  876. return false;
  877. return !getContext().DeclMustBeEmitted(Global);
  878. }
  879. llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
  880. const CXXUuidofExpr* E) {
  881. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  882. // well-formed.
  883. StringRef Uuid = E->getUuidAsStringRef(Context);
  884. std::string Name = "_GUID_" + Uuid.lower();
  885. std::replace(Name.begin(), Name.end(), '-', '_');
  886. // Look for an existing global.
  887. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  888. return GV;
  889. llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
  890. assert(Init && "failed to initialize as constant");
  891. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  892. getModule(), Init->getType(),
  893. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  894. return GV;
  895. }
  896. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  897. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  898. assert(AA && "No alias?");
  899. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  900. // See if there is already something with the target's name in the module.
  901. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  902. if (Entry) {
  903. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  904. return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  905. }
  906. llvm::Constant *Aliasee;
  907. if (isa<llvm::FunctionType>(DeclTy))
  908. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  909. GlobalDecl(cast<FunctionDecl>(VD)),
  910. /*ForVTable=*/false);
  911. else
  912. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  913. llvm::PointerType::getUnqual(DeclTy), 0);
  914. llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
  915. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  916. WeakRefReferences.insert(F);
  917. return Aliasee;
  918. }
  919. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  920. const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
  921. // Weak references don't produce any output by themselves.
  922. if (Global->hasAttr<WeakRefAttr>())
  923. return;
  924. // If this is an alias definition (which otherwise looks like a declaration)
  925. // emit it now.
  926. if (Global->hasAttr<AliasAttr>())
  927. return EmitAliasDefinition(GD);
  928. // If this is CUDA, be selective about which declarations we emit.
  929. if (LangOpts.CUDA) {
  930. if (CodeGenOpts.CUDAIsDevice) {
  931. if (!Global->hasAttr<CUDADeviceAttr>() &&
  932. !Global->hasAttr<CUDAGlobalAttr>() &&
  933. !Global->hasAttr<CUDAConstantAttr>() &&
  934. !Global->hasAttr<CUDASharedAttr>())
  935. return;
  936. } else {
  937. if (!Global->hasAttr<CUDAHostAttr>() && (
  938. Global->hasAttr<CUDADeviceAttr>() ||
  939. Global->hasAttr<CUDAConstantAttr>() ||
  940. Global->hasAttr<CUDASharedAttr>()))
  941. return;
  942. }
  943. }
  944. // Ignore declarations, they will be emitted on their first use.
  945. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
  946. // Forward declarations are emitted lazily on first use.
  947. if (!FD->doesThisDeclarationHaveABody()) {
  948. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  949. return;
  950. const FunctionDecl *InlineDefinition = 0;
  951. FD->getBody(InlineDefinition);
  952. StringRef MangledName = getMangledName(GD);
  953. DeferredDecls.erase(MangledName);
  954. EmitGlobalDefinition(InlineDefinition);
  955. return;
  956. }
  957. } else {
  958. const VarDecl *VD = cast<VarDecl>(Global);
  959. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  960. if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
  961. return;
  962. }
  963. // Defer code generation when possible if this is a static definition, inline
  964. // function etc. These we only want to emit if they are used.
  965. if (!MayDeferGeneration(Global)) {
  966. // Emit the definition if it can't be deferred.
  967. EmitGlobalDefinition(GD);
  968. return;
  969. }
  970. // If we're deferring emission of a C++ variable with an
  971. // initializer, remember the order in which it appeared in the file.
  972. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  973. cast<VarDecl>(Global)->hasInit()) {
  974. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  975. CXXGlobalInits.push_back(0);
  976. }
  977. // If the value has already been used, add it directly to the
  978. // DeferredDeclsToEmit list.
  979. StringRef MangledName = getMangledName(GD);
  980. if (GetGlobalValue(MangledName))
  981. DeferredDeclsToEmit.push_back(GD);
  982. else {
  983. // Otherwise, remember that we saw a deferred decl with this name. The
  984. // first use of the mangled name will cause it to move into
  985. // DeferredDeclsToEmit.
  986. DeferredDecls[MangledName] = GD;
  987. }
  988. }
  989. namespace {
  990. struct FunctionIsDirectlyRecursive :
  991. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  992. const StringRef Name;
  993. const Builtin::Context &BI;
  994. bool Result;
  995. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  996. Name(N), BI(C), Result(false) {
  997. }
  998. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  999. bool TraverseCallExpr(CallExpr *E) {
  1000. const FunctionDecl *FD = E->getDirectCallee();
  1001. if (!FD)
  1002. return true;
  1003. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1004. if (Attr && Name == Attr->getLabel()) {
  1005. Result = true;
  1006. return false;
  1007. }
  1008. unsigned BuiltinID = FD->getBuiltinID();
  1009. if (!BuiltinID)
  1010. return true;
  1011. StringRef BuiltinName = BI.GetName(BuiltinID);
  1012. if (BuiltinName.startswith("__builtin_") &&
  1013. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1014. Result = true;
  1015. return false;
  1016. }
  1017. return true;
  1018. }
  1019. };
  1020. }
  1021. // isTriviallyRecursive - Check if this function calls another
  1022. // decl that, because of the asm attribute or the other decl being a builtin,
  1023. // ends up pointing to itself.
  1024. bool
  1025. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1026. StringRef Name;
  1027. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1028. // asm labels are a special kind of mangling we have to support.
  1029. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1030. if (!Attr)
  1031. return false;
  1032. Name = Attr->getLabel();
  1033. } else {
  1034. Name = FD->getName();
  1035. }
  1036. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1037. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1038. return Walker.Result;
  1039. }
  1040. bool
  1041. CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1042. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1043. return true;
  1044. const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
  1045. if (CodeGenOpts.OptimizationLevel == 0 &&
  1046. !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
  1047. return false;
  1048. // PR9614. Avoid cases where the source code is lying to us. An available
  1049. // externally function should have an equivalent function somewhere else,
  1050. // but a function that calls itself is clearly not equivalent to the real
  1051. // implementation.
  1052. // This happens in glibc's btowc and in some configure checks.
  1053. return !isTriviallyRecursive(F);
  1054. }
  1055. /// If the type for the method's class was generated by
  1056. /// CGDebugInfo::createContextChain(), the cache contains only a
  1057. /// limited DIType without any declarations. Since EmitFunctionStart()
  1058. /// needs to find the canonical declaration for each method, we need
  1059. /// to construct the complete type prior to emitting the method.
  1060. void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
  1061. if (!D->isInstance())
  1062. return;
  1063. if (CGDebugInfo *DI = getModuleDebugInfo())
  1064. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
  1065. const PointerType *ThisPtr =
  1066. cast<PointerType>(D->getThisType(getContext()));
  1067. DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
  1068. }
  1069. }
  1070. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
  1071. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1072. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1073. Context.getSourceManager(),
  1074. "Generating code for declaration");
  1075. if (isa<FunctionDecl>(D)) {
  1076. // At -O0, don't generate IR for functions with available_externally
  1077. // linkage.
  1078. if (!shouldEmitFunction(GD))
  1079. return;
  1080. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  1081. CompleteDIClassType(Method);
  1082. // Make sure to emit the definition(s) before we emit the thunks.
  1083. // This is necessary for the generation of certain thunks.
  1084. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
  1085. EmitCXXConstructor(CD, GD.getCtorType());
  1086. else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
  1087. EmitCXXDestructor(DD, GD.getDtorType());
  1088. else
  1089. EmitGlobalFunctionDefinition(GD);
  1090. if (Method->isVirtual())
  1091. getVTables().EmitThunks(GD);
  1092. return;
  1093. }
  1094. return EmitGlobalFunctionDefinition(GD);
  1095. }
  1096. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1097. return EmitGlobalVarDefinition(VD);
  1098. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1099. }
  1100. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1101. /// module, create and return an llvm Function with the specified type. If there
  1102. /// is something in the module with the specified name, return it potentially
  1103. /// bitcasted to the right type.
  1104. ///
  1105. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1106. /// to set the attributes on the function when it is first created.
  1107. llvm::Constant *
  1108. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  1109. llvm::Type *Ty,
  1110. GlobalDecl GD, bool ForVTable,
  1111. llvm::AttributeSet ExtraAttrs) {
  1112. const Decl *D = GD.getDecl();
  1113. // Lookup the entry, lazily creating it if necessary.
  1114. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1115. if (Entry) {
  1116. if (WeakRefReferences.erase(Entry)) {
  1117. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1118. if (FD && !FD->hasAttr<WeakAttr>())
  1119. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1120. }
  1121. if (Entry->getType()->getElementType() == Ty)
  1122. return Entry;
  1123. // Make sure the result is of the correct type.
  1124. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1125. }
  1126. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1127. // each other bottoming out with the base dtor. Therefore we emit non-base
  1128. // dtors on usage, even if there is no dtor definition in the TU.
  1129. if (D && isa<CXXDestructorDecl>(D) &&
  1130. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1131. GD.getDtorType()))
  1132. DeferredDeclsToEmit.push_back(GD);
  1133. // This function doesn't have a complete type (for example, the return
  1134. // type is an incomplete struct). Use a fake type instead, and make
  1135. // sure not to try to set attributes.
  1136. bool IsIncompleteFunction = false;
  1137. llvm::FunctionType *FTy;
  1138. if (isa<llvm::FunctionType>(Ty)) {
  1139. FTy = cast<llvm::FunctionType>(Ty);
  1140. } else {
  1141. FTy = llvm::FunctionType::get(VoidTy, false);
  1142. IsIncompleteFunction = true;
  1143. }
  1144. llvm::Function *F = llvm::Function::Create(FTy,
  1145. llvm::Function::ExternalLinkage,
  1146. MangledName, &getModule());
  1147. assert(F->getName() == MangledName && "name was uniqued!");
  1148. if (D)
  1149. SetFunctionAttributes(GD, F, IsIncompleteFunction);
  1150. if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
  1151. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
  1152. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  1153. llvm::AttributeSet::get(VMContext,
  1154. llvm::AttributeSet::FunctionIndex,
  1155. B));
  1156. }
  1157. // This is the first use or definition of a mangled name. If there is a
  1158. // deferred decl with this name, remember that we need to emit it at the end
  1159. // of the file.
  1160. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  1161. if (DDI != DeferredDecls.end()) {
  1162. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1163. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1164. DeferredDeclsToEmit.push_back(DDI->second);
  1165. DeferredDecls.erase(DDI);
  1166. // Otherwise, there are cases we have to worry about where we're
  1167. // using a declaration for which we must emit a definition but where
  1168. // we might not find a top-level definition:
  1169. // - member functions defined inline in their classes
  1170. // - friend functions defined inline in some class
  1171. // - special member functions with implicit definitions
  1172. // If we ever change our AST traversal to walk into class methods,
  1173. // this will be unnecessary.
  1174. //
  1175. // We also don't emit a definition for a function if it's going to be an entry
  1176. // in a vtable, unless it's already marked as used.
  1177. } else if (getLangOpts().CPlusPlus && D) {
  1178. // Look for a declaration that's lexically in a record.
  1179. const FunctionDecl *FD = cast<FunctionDecl>(D);
  1180. FD = FD->getMostRecentDecl();
  1181. do {
  1182. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1183. if (FD->isImplicit() && !ForVTable) {
  1184. assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
  1185. DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
  1186. break;
  1187. } else if (FD->doesThisDeclarationHaveABody()) {
  1188. DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
  1189. break;
  1190. }
  1191. }
  1192. FD = FD->getPreviousDecl();
  1193. } while (FD);
  1194. }
  1195. // Make sure the result is of the requested type.
  1196. if (!IsIncompleteFunction) {
  1197. assert(F->getType()->getElementType() == Ty);
  1198. return F;
  1199. }
  1200. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1201. return llvm::ConstantExpr::getBitCast(F, PTy);
  1202. }
  1203. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1204. /// non-null, then this function will use the specified type if it has to
  1205. /// create it (this occurs when we see a definition of the function).
  1206. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1207. llvm::Type *Ty,
  1208. bool ForVTable) {
  1209. // If there was no specific requested type, just convert it now.
  1210. if (!Ty)
  1211. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  1212. StringRef MangledName = getMangledName(GD);
  1213. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
  1214. }
  1215. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1216. /// type and name.
  1217. llvm::Constant *
  1218. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  1219. StringRef Name,
  1220. llvm::AttributeSet ExtraAttrs) {
  1221. llvm::Constant *C
  1222. = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1223. ExtraAttrs);
  1224. if (llvm::Function *F = dyn_cast<llvm::Function>(C))
  1225. if (F->empty())
  1226. F->setCallingConv(getRuntimeCC());
  1227. return C;
  1228. }
  1229. /// isTypeConstant - Determine whether an object of this type can be emitted
  1230. /// as a constant.
  1231. ///
  1232. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1233. /// will not be considered. The caller will need to verify that the object is
  1234. /// not written to during its construction.
  1235. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1236. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1237. return false;
  1238. if (Context.getLangOpts().CPlusPlus) {
  1239. if (const CXXRecordDecl *Record
  1240. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1241. return ExcludeCtor && !Record->hasMutableFields() &&
  1242. Record->hasTrivialDestructor();
  1243. }
  1244. return true;
  1245. }
  1246. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1247. /// create and return an llvm GlobalVariable with the specified type. If there
  1248. /// is something in the module with the specified name, return it potentially
  1249. /// bitcasted to the right type.
  1250. ///
  1251. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1252. /// to set the attributes on the global when it is first created.
  1253. llvm::Constant *
  1254. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1255. llvm::PointerType *Ty,
  1256. const VarDecl *D,
  1257. bool UnnamedAddr) {
  1258. // Lookup the entry, lazily creating it if necessary.
  1259. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1260. if (Entry) {
  1261. if (WeakRefReferences.erase(Entry)) {
  1262. if (D && !D->hasAttr<WeakAttr>())
  1263. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1264. }
  1265. if (UnnamedAddr)
  1266. Entry->setUnnamedAddr(true);
  1267. if (Entry->getType() == Ty)
  1268. return Entry;
  1269. // Make sure the result is of the correct type.
  1270. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1271. }
  1272. // This is the first use or definition of a mangled name. If there is a
  1273. // deferred decl with this name, remember that we need to emit it at the end
  1274. // of the file.
  1275. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  1276. if (DDI != DeferredDecls.end()) {
  1277. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1278. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1279. DeferredDeclsToEmit.push_back(DDI->second);
  1280. DeferredDecls.erase(DDI);
  1281. }
  1282. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1283. llvm::GlobalVariable *GV =
  1284. new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
  1285. llvm::GlobalValue::ExternalLinkage,
  1286. 0, MangledName, 0,
  1287. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1288. // Handle things which are present even on external declarations.
  1289. if (D) {
  1290. // FIXME: This code is overly simple and should be merged with other global
  1291. // handling.
  1292. GV->setConstant(isTypeConstant(D->getType(), false));
  1293. // Set linkage and visibility in case we never see a definition.
  1294. LinkageInfo LV = D->getLinkageAndVisibility();
  1295. if (LV.getLinkage() != ExternalLinkage) {
  1296. // Don't set internal linkage on declarations.
  1297. } else {
  1298. if (D->hasAttr<DLLImportAttr>())
  1299. GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
  1300. else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
  1301. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1302. // Set visibility on a declaration only if it's explicit.
  1303. if (LV.isVisibilityExplicit())
  1304. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  1305. }
  1306. if (D->getTLSKind()) {
  1307. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1308. CXXThreadLocals.push_back(std::make_pair(D, GV));
  1309. setTLSMode(GV, *D);
  1310. }
  1311. }
  1312. if (AddrSpace != Ty->getAddressSpace())
  1313. return llvm::ConstantExpr::getBitCast(GV, Ty);
  1314. else
  1315. return GV;
  1316. }
  1317. llvm::GlobalVariable *
  1318. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1319. llvm::Type *Ty,
  1320. llvm::GlobalValue::LinkageTypes Linkage) {
  1321. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1322. llvm::GlobalVariable *OldGV = 0;
  1323. if (GV) {
  1324. // Check if the variable has the right type.
  1325. if (GV->getType()->getElementType() == Ty)
  1326. return GV;
  1327. // Because C++ name mangling, the only way we can end up with an already
  1328. // existing global with the same name is if it has been declared extern "C".
  1329. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1330. OldGV = GV;
  1331. }
  1332. // Create a new variable.
  1333. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1334. Linkage, 0, Name);
  1335. if (OldGV) {
  1336. // Replace occurrences of the old variable if needed.
  1337. GV->takeName(OldGV);
  1338. if (!OldGV->use_empty()) {
  1339. llvm::Constant *NewPtrForOldDecl =
  1340. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1341. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1342. }
  1343. OldGV->eraseFromParent();
  1344. }
  1345. return GV;
  1346. }
  1347. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1348. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1349. /// then it will be created with the specified type instead of whatever the
  1350. /// normal requested type would be.
  1351. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1352. llvm::Type *Ty) {
  1353. assert(D->hasGlobalStorage() && "Not a global variable");
  1354. QualType ASTTy = D->getType();
  1355. if (Ty == 0)
  1356. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1357. llvm::PointerType *PTy =
  1358. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1359. StringRef MangledName = getMangledName(D);
  1360. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1361. }
  1362. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1363. /// specified type and name.
  1364. llvm::Constant *
  1365. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1366. StringRef Name) {
  1367. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
  1368. true);
  1369. }
  1370. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1371. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1372. if (MayDeferGeneration(D)) {
  1373. // If we have not seen a reference to this variable yet, place it
  1374. // into the deferred declarations table to be emitted if needed
  1375. // later.
  1376. StringRef MangledName = getMangledName(D);
  1377. if (!GetGlobalValue(MangledName)) {
  1378. DeferredDecls[MangledName] = D;
  1379. return;
  1380. }
  1381. }
  1382. // The tentative definition is the only definition.
  1383. EmitGlobalVarDefinition(D);
  1384. }
  1385. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1386. return Context.toCharUnitsFromBits(
  1387. TheDataLayout.getTypeStoreSizeInBits(Ty));
  1388. }
  1389. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1390. unsigned AddrSpace) {
  1391. if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
  1392. if (D->hasAttr<CUDAConstantAttr>())
  1393. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1394. else if (D->hasAttr<CUDASharedAttr>())
  1395. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1396. else
  1397. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1398. }
  1399. return AddrSpace;
  1400. }
  1401. template<typename SomeDecl>
  1402. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  1403. llvm::GlobalValue *GV) {
  1404. if (!getLangOpts().CPlusPlus)
  1405. return;
  1406. // Must have 'used' attribute, or else inline assembly can't rely on
  1407. // the name existing.
  1408. if (!D->template hasAttr<UsedAttr>())
  1409. return;
  1410. // Must have internal linkage and an ordinary name.
  1411. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  1412. return;
  1413. // Must be in an extern "C" context. Entities declared directly within
  1414. // a record are not extern "C" even if the record is in such a context.
  1415. const SomeDecl *First = D->getFirstDecl();
  1416. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  1417. return;
  1418. // OK, this is an internal linkage entity inside an extern "C" linkage
  1419. // specification. Make a note of that so we can give it the "expected"
  1420. // mangled name if nothing else is using that name.
  1421. std::pair<StaticExternCMap::iterator, bool> R =
  1422. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  1423. // If we have multiple internal linkage entities with the same name
  1424. // in extern "C" regions, none of them gets that name.
  1425. if (!R.second)
  1426. R.first->second = 0;
  1427. }
  1428. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1429. llvm::Constant *Init = 0;
  1430. QualType ASTTy = D->getType();
  1431. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1432. bool NeedsGlobalCtor = false;
  1433. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1434. const VarDecl *InitDecl;
  1435. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1436. if (!InitExpr) {
  1437. // This is a tentative definition; tentative definitions are
  1438. // implicitly initialized with { 0 }.
  1439. //
  1440. // Note that tentative definitions are only emitted at the end of
  1441. // a translation unit, so they should never have incomplete
  1442. // type. In addition, EmitTentativeDefinition makes sure that we
  1443. // never attempt to emit a tentative definition if a real one
  1444. // exists. A use may still exists, however, so we still may need
  1445. // to do a RAUW.
  1446. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1447. Init = EmitNullConstant(D->getType());
  1448. } else {
  1449. initializedGlobalDecl = GlobalDecl(D);
  1450. Init = EmitConstantInit(*InitDecl);
  1451. if (!Init) {
  1452. QualType T = InitExpr->getType();
  1453. if (D->getType()->isReferenceType())
  1454. T = D->getType();
  1455. if (getLangOpts().CPlusPlus) {
  1456. Init = EmitNullConstant(T);
  1457. NeedsGlobalCtor = true;
  1458. } else {
  1459. ErrorUnsupported(D, "static initializer");
  1460. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1461. }
  1462. } else {
  1463. // We don't need an initializer, so remove the entry for the delayed
  1464. // initializer position (just in case this entry was delayed) if we
  1465. // also don't need to register a destructor.
  1466. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1467. DelayedCXXInitPosition.erase(D);
  1468. }
  1469. }
  1470. llvm::Type* InitType = Init->getType();
  1471. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1472. // Strip off a bitcast if we got one back.
  1473. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1474. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1475. // all zero index gep.
  1476. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1477. Entry = CE->getOperand(0);
  1478. }
  1479. // Entry is now either a Function or GlobalVariable.
  1480. llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1481. // We have a definition after a declaration with the wrong type.
  1482. // We must make a new GlobalVariable* and update everything that used OldGV
  1483. // (a declaration or tentative definition) with the new GlobalVariable*
  1484. // (which will be a definition).
  1485. //
  1486. // This happens if there is a prototype for a global (e.g.
  1487. // "extern int x[];") and then a definition of a different type (e.g.
  1488. // "int x[10];"). This also happens when an initializer has a different type
  1489. // from the type of the global (this happens with unions).
  1490. if (GV == 0 ||
  1491. GV->getType()->getElementType() != InitType ||
  1492. GV->getType()->getAddressSpace() !=
  1493. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  1494. // Move the old entry aside so that we'll create a new one.
  1495. Entry->setName(StringRef());
  1496. // Make a new global with the correct type, this is now guaranteed to work.
  1497. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1498. // Replace all uses of the old global with the new global
  1499. llvm::Constant *NewPtrForOldDecl =
  1500. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1501. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1502. // Erase the old global, since it is no longer used.
  1503. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1504. }
  1505. MaybeHandleStaticInExternC(D, GV);
  1506. if (D->hasAttr<AnnotateAttr>())
  1507. AddGlobalAnnotations(D, GV);
  1508. GV->setInitializer(Init);
  1509. // If it is safe to mark the global 'constant', do so now.
  1510. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1511. isTypeConstant(D->getType(), true));
  1512. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1513. // Set the llvm linkage type as appropriate.
  1514. llvm::GlobalValue::LinkageTypes Linkage =
  1515. GetLLVMLinkageVarDefinition(D, GV->isConstant());
  1516. GV->setLinkage(Linkage);
  1517. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1518. // common vars aren't constant even if declared const.
  1519. GV->setConstant(false);
  1520. SetCommonAttributes(D, GV);
  1521. // Emit the initializer function if necessary.
  1522. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1523. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1524. // If we are compiling with ASan, add metadata indicating dynamically
  1525. // initialized globals.
  1526. if (SanOpts.Address && NeedsGlobalCtor) {
  1527. llvm::Module &M = getModule();
  1528. llvm::NamedMDNode *DynamicInitializers =
  1529. M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
  1530. llvm::Value *GlobalToAdd[] = { GV };
  1531. llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
  1532. DynamicInitializers->addOperand(ThisGlobal);
  1533. }
  1534. // Emit global variable debug information.
  1535. if (CGDebugInfo *DI = getModuleDebugInfo())
  1536. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1537. DI->EmitGlobalVariable(GV, D);
  1538. }
  1539. llvm::GlobalValue::LinkageTypes
  1540. CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
  1541. GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
  1542. if (Linkage == GVA_Internal)
  1543. return llvm::Function::InternalLinkage;
  1544. else if (D->hasAttr<DLLImportAttr>())
  1545. return llvm::Function::DLLImportLinkage;
  1546. else if (D->hasAttr<DLLExportAttr>())
  1547. return llvm::Function::DLLExportLinkage;
  1548. else if (D->hasAttr<SelectAnyAttr>()) {
  1549. // selectany symbols are externally visible, so use weak instead of
  1550. // linkonce. MSVC optimizes away references to const selectany globals, so
  1551. // all definitions should be the same and ODR linkage should be used.
  1552. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  1553. return llvm::GlobalVariable::WeakODRLinkage;
  1554. } else if (D->hasAttr<WeakAttr>()) {
  1555. if (isConstant)
  1556. return llvm::GlobalVariable::WeakODRLinkage;
  1557. else
  1558. return llvm::GlobalVariable::WeakAnyLinkage;
  1559. } else if (Linkage == GVA_TemplateInstantiation ||
  1560. Linkage == GVA_ExplicitTemplateInstantiation)
  1561. return llvm::GlobalVariable::WeakODRLinkage;
  1562. else if (!getLangOpts().CPlusPlus &&
  1563. ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
  1564. D->getAttr<CommonAttr>()) &&
  1565. !D->hasExternalStorage() && !D->getInit() &&
  1566. !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
  1567. !D->getAttr<WeakImportAttr>()) {
  1568. // Thread local vars aren't considered common linkage.
  1569. return llvm::GlobalVariable::CommonLinkage;
  1570. } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
  1571. getTarget().getTriple().isMacOSX())
  1572. // On Darwin, the backing variable for a C++11 thread_local variable always
  1573. // has internal linkage; all accesses should just be calls to the
  1574. // Itanium-specified entry point, which has the normal linkage of the
  1575. // variable.
  1576. return llvm::GlobalValue::InternalLinkage;
  1577. return llvm::GlobalVariable::ExternalLinkage;
  1578. }
  1579. /// Replace the uses of a function that was declared with a non-proto type.
  1580. /// We want to silently drop extra arguments from call sites
  1581. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  1582. llvm::Function *newFn) {
  1583. // Fast path.
  1584. if (old->use_empty()) return;
  1585. llvm::Type *newRetTy = newFn->getReturnType();
  1586. SmallVector<llvm::Value*, 4> newArgs;
  1587. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  1588. ui != ue; ) {
  1589. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  1590. llvm::User *user = *use;
  1591. // Recognize and replace uses of bitcasts. Most calls to
  1592. // unprototyped functions will use bitcasts.
  1593. if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  1594. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  1595. replaceUsesOfNonProtoConstant(bitcast, newFn);
  1596. continue;
  1597. }
  1598. // Recognize calls to the function.
  1599. llvm::CallSite callSite(user);
  1600. if (!callSite) continue;
  1601. if (!callSite.isCallee(use)) continue;
  1602. // If the return types don't match exactly, then we can't
  1603. // transform this call unless it's dead.
  1604. if (callSite->getType() != newRetTy && !callSite->use_empty())
  1605. continue;
  1606. // Get the call site's attribute list.
  1607. SmallVector<llvm::AttributeSet, 8> newAttrs;
  1608. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  1609. // Collect any return attributes from the call.
  1610. if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
  1611. newAttrs.push_back(
  1612. llvm::AttributeSet::get(newFn->getContext(),
  1613. oldAttrs.getRetAttributes()));
  1614. // If the function was passed too few arguments, don't transform.
  1615. unsigned newNumArgs = newFn->arg_size();
  1616. if (callSite.arg_size() < newNumArgs) continue;
  1617. // If extra arguments were passed, we silently drop them.
  1618. // If any of the types mismatch, we don't transform.
  1619. unsigned argNo = 0;
  1620. bool dontTransform = false;
  1621. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  1622. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  1623. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  1624. dontTransform = true;
  1625. break;
  1626. }
  1627. // Add any parameter attributes.
  1628. if (oldAttrs.hasAttributes(argNo + 1))
  1629. newAttrs.
  1630. push_back(llvm::
  1631. AttributeSet::get(newFn->getContext(),
  1632. oldAttrs.getParamAttributes(argNo + 1)));
  1633. }
  1634. if (dontTransform)
  1635. continue;
  1636. if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
  1637. newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
  1638. oldAttrs.getFnAttributes()));
  1639. // Okay, we can transform this. Create the new call instruction and copy
  1640. // over the required information.
  1641. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  1642. llvm::CallSite newCall;
  1643. if (callSite.isCall()) {
  1644. newCall = llvm::CallInst::Create(newFn, newArgs, "",
  1645. callSite.getInstruction());
  1646. } else {
  1647. llvm::InvokeInst *oldInvoke =
  1648. cast<llvm::InvokeInst>(callSite.getInstruction());
  1649. newCall = llvm::InvokeInst::Create(newFn,
  1650. oldInvoke->getNormalDest(),
  1651. oldInvoke->getUnwindDest(),
  1652. newArgs, "",
  1653. callSite.getInstruction());
  1654. }
  1655. newArgs.clear(); // for the next iteration
  1656. if (!newCall->getType()->isVoidTy())
  1657. newCall->takeName(callSite.getInstruction());
  1658. newCall.setAttributes(
  1659. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  1660. newCall.setCallingConv(callSite.getCallingConv());
  1661. // Finally, remove the old call, replacing any uses with the new one.
  1662. if (!callSite->use_empty())
  1663. callSite->replaceAllUsesWith(newCall.getInstruction());
  1664. // Copy debug location attached to CI.
  1665. if (!callSite->getDebugLoc().isUnknown())
  1666. newCall->setDebugLoc(callSite->getDebugLoc());
  1667. callSite->eraseFromParent();
  1668. }
  1669. }
  1670. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1671. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1672. /// existing call uses of the old function in the module, this adjusts them to
  1673. /// call the new function directly.
  1674. ///
  1675. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1676. /// functions to be able to inline them. If there is a bitcast in the way, it
  1677. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1678. /// run at -O0.
  1679. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1680. llvm::Function *NewFn) {
  1681. // If we're redefining a global as a function, don't transform it.
  1682. if (!isa<llvm::Function>(Old)) return;
  1683. replaceUsesOfNonProtoConstant(Old, NewFn);
  1684. }
  1685. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  1686. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  1687. // If we have a definition, this might be a deferred decl. If the
  1688. // instantiation is explicit, make sure we emit it at the end.
  1689. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  1690. GetAddrOfGlobalVar(VD);
  1691. EmitTopLevelDecl(VD);
  1692. }
  1693. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
  1694. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  1695. // Compute the function info and LLVM type.
  1696. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1697. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1698. // Get or create the prototype for the function.
  1699. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
  1700. // Strip off a bitcast if we got one back.
  1701. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1702. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1703. Entry = CE->getOperand(0);
  1704. }
  1705. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
  1706. llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
  1707. // If the types mismatch then we have to rewrite the definition.
  1708. assert(OldFn->isDeclaration() &&
  1709. "Shouldn't replace non-declaration");
  1710. // F is the Function* for the one with the wrong type, we must make a new
  1711. // Function* and update everything that used F (a declaration) with the new
  1712. // Function* (which will be a definition).
  1713. //
  1714. // This happens if there is a prototype for a function
  1715. // (e.g. "int f()") and then a definition of a different type
  1716. // (e.g. "int f(int x)"). Move the old function aside so that it
  1717. // doesn't interfere with GetAddrOfFunction.
  1718. OldFn->setName(StringRef());
  1719. llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1720. // This might be an implementation of a function without a
  1721. // prototype, in which case, try to do special replacement of
  1722. // calls which match the new prototype. The really key thing here
  1723. // is that we also potentially drop arguments from the call site
  1724. // so as to make a direct call, which makes the inliner happier
  1725. // and suppresses a number of optimizer warnings (!) about
  1726. // dropping arguments.
  1727. if (!OldFn->use_empty()) {
  1728. ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
  1729. OldFn->removeDeadConstantUsers();
  1730. }
  1731. // Replace uses of F with the Function we will endow with a body.
  1732. if (!Entry->use_empty()) {
  1733. llvm::Constant *NewPtrForOldDecl =
  1734. llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
  1735. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1736. }
  1737. // Ok, delete the old function now, which is dead.
  1738. OldFn->eraseFromParent();
  1739. Entry = NewFn;
  1740. }
  1741. // We need to set linkage and visibility on the function before
  1742. // generating code for it because various parts of IR generation
  1743. // want to propagate this information down (e.g. to local static
  1744. // declarations).
  1745. llvm::Function *Fn = cast<llvm::Function>(Entry);
  1746. setFunctionLinkage(GD, Fn);
  1747. // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
  1748. setGlobalVisibility(Fn, D);
  1749. MaybeHandleStaticInExternC(D, Fn);
  1750. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  1751. SetFunctionDefinitionAttributes(D, Fn);
  1752. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1753. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1754. AddGlobalCtor(Fn, CA->getPriority());
  1755. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1756. AddGlobalDtor(Fn, DA->getPriority());
  1757. if (D->hasAttr<AnnotateAttr>())
  1758. AddGlobalAnnotations(D, Fn);
  1759. }
  1760. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1761. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1762. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1763. assert(AA && "Not an alias?");
  1764. StringRef MangledName = getMangledName(GD);
  1765. // If there is a definition in the module, then it wins over the alias.
  1766. // This is dubious, but allow it to be safe. Just ignore the alias.
  1767. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1768. if (Entry && !Entry->isDeclaration())
  1769. return;
  1770. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1771. // Create a reference to the named value. This ensures that it is emitted
  1772. // if a deferred decl.
  1773. llvm::Constant *Aliasee;
  1774. if (isa<llvm::FunctionType>(DeclTy))
  1775. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  1776. /*ForVTable=*/false);
  1777. else
  1778. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1779. llvm::PointerType::getUnqual(DeclTy), 0);
  1780. // Create the new alias itself, but don't set a name yet.
  1781. llvm::GlobalValue *GA =
  1782. new llvm::GlobalAlias(Aliasee->getType(),
  1783. llvm::Function::ExternalLinkage,
  1784. "", Aliasee, &getModule());
  1785. if (Entry) {
  1786. assert(Entry->isDeclaration());
  1787. // If there is a declaration in the module, then we had an extern followed
  1788. // by the alias, as in:
  1789. // extern int test6();
  1790. // ...
  1791. // int test6() __attribute__((alias("test7")));
  1792. //
  1793. // Remove it and replace uses of it with the alias.
  1794. GA->takeName(Entry);
  1795. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1796. Entry->getType()));
  1797. Entry->eraseFromParent();
  1798. } else {
  1799. GA->setName(MangledName);
  1800. }
  1801. // Set attributes which are particular to an alias; this is a
  1802. // specialization of the attributes which may be set on a global
  1803. // variable/function.
  1804. if (D->hasAttr<DLLExportAttr>()) {
  1805. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1806. // The dllexport attribute is ignored for undefined symbols.
  1807. if (FD->hasBody())
  1808. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1809. } else {
  1810. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1811. }
  1812. } else if (D->hasAttr<WeakAttr>() ||
  1813. D->hasAttr<WeakRefAttr>() ||
  1814. D->isWeakImported()) {
  1815. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1816. }
  1817. SetCommonAttributes(D, GA);
  1818. }
  1819. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  1820. ArrayRef<llvm::Type*> Tys) {
  1821. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  1822. Tys);
  1823. }
  1824. static llvm::StringMapEntry<llvm::Constant*> &
  1825. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1826. const StringLiteral *Literal,
  1827. bool TargetIsLSB,
  1828. bool &IsUTF16,
  1829. unsigned &StringLength) {
  1830. StringRef String = Literal->getString();
  1831. unsigned NumBytes = String.size();
  1832. // Check for simple case.
  1833. if (!Literal->containsNonAsciiOrNull()) {
  1834. StringLength = NumBytes;
  1835. return Map.GetOrCreateValue(String);
  1836. }
  1837. // Otherwise, convert the UTF8 literals into a string of shorts.
  1838. IsUTF16 = true;
  1839. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  1840. const UTF8 *FromPtr = (const UTF8 *)String.data();
  1841. UTF16 *ToPtr = &ToBuf[0];
  1842. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1843. &ToPtr, ToPtr + NumBytes,
  1844. strictConversion);
  1845. // ConvertUTF8toUTF16 returns the length in ToPtr.
  1846. StringLength = ToPtr - &ToBuf[0];
  1847. // Add an explicit null.
  1848. *ToPtr = 0;
  1849. return Map.
  1850. GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  1851. (StringLength + 1) * 2));
  1852. }
  1853. static llvm::StringMapEntry<llvm::Constant*> &
  1854. GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1855. const StringLiteral *Literal,
  1856. unsigned &StringLength) {
  1857. StringRef String = Literal->getString();
  1858. StringLength = String.size();
  1859. return Map.GetOrCreateValue(String);
  1860. }
  1861. llvm::Constant *
  1862. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  1863. unsigned StringLength = 0;
  1864. bool isUTF16 = false;
  1865. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1866. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1867. getDataLayout().isLittleEndian(),
  1868. isUTF16, StringLength);
  1869. if (llvm::Constant *C = Entry.getValue())
  1870. return C;
  1871. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1872. llvm::Constant *Zeros[] = { Zero, Zero };
  1873. llvm::Value *V;
  1874. // If we don't already have it, get __CFConstantStringClassReference.
  1875. if (!CFConstantStringClassRef) {
  1876. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1877. Ty = llvm::ArrayType::get(Ty, 0);
  1878. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  1879. "__CFConstantStringClassReference");
  1880. // Decay array -> ptr
  1881. V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1882. CFConstantStringClassRef = V;
  1883. }
  1884. else
  1885. V = CFConstantStringClassRef;
  1886. QualType CFTy = getContext().getCFConstantStringType();
  1887. llvm::StructType *STy =
  1888. cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  1889. llvm::Constant *Fields[4];
  1890. // Class pointer.
  1891. Fields[0] = cast<llvm::ConstantExpr>(V);
  1892. // Flags.
  1893. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1894. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  1895. llvm::ConstantInt::get(Ty, 0x07C8);
  1896. // String pointer.
  1897. llvm::Constant *C = 0;
  1898. if (isUTF16) {
  1899. ArrayRef<uint16_t> Arr =
  1900. llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
  1901. const_cast<char *>(Entry.getKey().data())),
  1902. Entry.getKey().size() / 2);
  1903. C = llvm::ConstantDataArray::get(VMContext, Arr);
  1904. } else {
  1905. C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1906. }
  1907. llvm::GlobalValue::LinkageTypes Linkage;
  1908. if (isUTF16)
  1909. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1910. Linkage = llvm::GlobalValue::InternalLinkage;
  1911. else
  1912. // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
  1913. // when using private linkage. It is not clear if this is a bug in ld
  1914. // or a reasonable new restriction.
  1915. Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
  1916. // Note: -fwritable-strings doesn't make the backing store strings of
  1917. // CFStrings writable. (See <rdar://problem/10657500>)
  1918. llvm::GlobalVariable *GV =
  1919. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  1920. Linkage, C, ".str");
  1921. GV->setUnnamedAddr(true);
  1922. // Don't enforce the target's minimum global alignment, since the only use
  1923. // of the string is via this class initializer.
  1924. if (isUTF16) {
  1925. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1926. GV->setAlignment(Align.getQuantity());
  1927. } else {
  1928. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1929. GV->setAlignment(Align.getQuantity());
  1930. }
  1931. // String.
  1932. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1933. if (isUTF16)
  1934. // Cast the UTF16 string to the correct type.
  1935. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  1936. // String length.
  1937. Ty = getTypes().ConvertType(getContext().LongTy);
  1938. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  1939. // The struct.
  1940. C = llvm::ConstantStruct::get(STy, Fields);
  1941. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1942. llvm::GlobalVariable::PrivateLinkage, C,
  1943. "_unnamed_cfstring_");
  1944. if (const char *Sect = getTarget().getCFStringSection())
  1945. GV->setSection(Sect);
  1946. Entry.setValue(GV);
  1947. return GV;
  1948. }
  1949. static RecordDecl *
  1950. CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
  1951. DeclContext *DC, IdentifierInfo *Id) {
  1952. SourceLocation Loc;
  1953. if (Ctx.getLangOpts().CPlusPlus)
  1954. return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1955. else
  1956. return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1957. }
  1958. llvm::Constant *
  1959. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  1960. unsigned StringLength = 0;
  1961. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1962. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  1963. if (llvm::Constant *C = Entry.getValue())
  1964. return C;
  1965. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1966. llvm::Constant *Zeros[] = { Zero, Zero };
  1967. llvm::Value *V;
  1968. // If we don't already have it, get _NSConstantStringClassReference.
  1969. if (!ConstantStringClassRef) {
  1970. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  1971. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1972. llvm::Constant *GV;
  1973. if (LangOpts.ObjCRuntime.isNonFragile()) {
  1974. std::string str =
  1975. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  1976. : "OBJC_CLASS_$_" + StringClass;
  1977. GV = getObjCRuntime().GetClassGlobal(str);
  1978. // Make sure the result is of the correct type.
  1979. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1980. V = llvm::ConstantExpr::getBitCast(GV, PTy);
  1981. ConstantStringClassRef = V;
  1982. } else {
  1983. std::string str =
  1984. StringClass.empty() ? "_NSConstantStringClassReference"
  1985. : "_" + StringClass + "ClassReference";
  1986. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  1987. GV = CreateRuntimeVariable(PTy, str);
  1988. // Decay array -> ptr
  1989. V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1990. ConstantStringClassRef = V;
  1991. }
  1992. }
  1993. else
  1994. V = ConstantStringClassRef;
  1995. if (!NSConstantStringType) {
  1996. // Construct the type for a constant NSString.
  1997. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  1998. Context.getTranslationUnitDecl(),
  1999. &Context.Idents.get("__builtin_NSString"));
  2000. D->startDefinition();
  2001. QualType FieldTypes[3];
  2002. // const int *isa;
  2003. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  2004. // const char *str;
  2005. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  2006. // unsigned int length;
  2007. FieldTypes[2] = Context.UnsignedIntTy;
  2008. // Create fields
  2009. for (unsigned i = 0; i < 3; ++i) {
  2010. FieldDecl *Field = FieldDecl::Create(Context, D,
  2011. SourceLocation(),
  2012. SourceLocation(), 0,
  2013. FieldTypes[i], /*TInfo=*/0,
  2014. /*BitWidth=*/0,
  2015. /*Mutable=*/false,
  2016. ICIS_NoInit);
  2017. Field->setAccess(AS_public);
  2018. D->addDecl(Field);
  2019. }
  2020. D->completeDefinition();
  2021. QualType NSTy = Context.getTagDeclType(D);
  2022. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  2023. }
  2024. llvm::Constant *Fields[3];
  2025. // Class pointer.
  2026. Fields[0] = cast<llvm::ConstantExpr>(V);
  2027. // String pointer.
  2028. llvm::Constant *C =
  2029. llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  2030. llvm::GlobalValue::LinkageTypes Linkage;
  2031. bool isConstant;
  2032. Linkage = llvm::GlobalValue::PrivateLinkage;
  2033. isConstant = !LangOpts.WritableStrings;
  2034. llvm::GlobalVariable *GV =
  2035. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  2036. ".str");
  2037. GV->setUnnamedAddr(true);
  2038. // Don't enforce the target's minimum global alignment, since the only use
  2039. // of the string is via this class initializer.
  2040. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2041. GV->setAlignment(Align.getQuantity());
  2042. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  2043. // String length.
  2044. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2045. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  2046. // The struct.
  2047. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  2048. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2049. llvm::GlobalVariable::PrivateLinkage, C,
  2050. "_unnamed_nsstring_");
  2051. // FIXME. Fix section.
  2052. if (const char *Sect =
  2053. LangOpts.ObjCRuntime.isNonFragile()
  2054. ? getTarget().getNSStringNonFragileABISection()
  2055. : getTarget().getNSStringSection())
  2056. GV->setSection(Sect);
  2057. Entry.setValue(GV);
  2058. return GV;
  2059. }
  2060. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2061. if (ObjCFastEnumerationStateType.isNull()) {
  2062. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  2063. Context.getTranslationUnitDecl(),
  2064. &Context.Idents.get("__objcFastEnumerationState"));
  2065. D->startDefinition();
  2066. QualType FieldTypes[] = {
  2067. Context.UnsignedLongTy,
  2068. Context.getPointerType(Context.getObjCIdType()),
  2069. Context.getPointerType(Context.UnsignedLongTy),
  2070. Context.getConstantArrayType(Context.UnsignedLongTy,
  2071. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2072. };
  2073. for (size_t i = 0; i < 4; ++i) {
  2074. FieldDecl *Field = FieldDecl::Create(Context,
  2075. D,
  2076. SourceLocation(),
  2077. SourceLocation(), 0,
  2078. FieldTypes[i], /*TInfo=*/0,
  2079. /*BitWidth=*/0,
  2080. /*Mutable=*/false,
  2081. ICIS_NoInit);
  2082. Field->setAccess(AS_public);
  2083. D->addDecl(Field);
  2084. }
  2085. D->completeDefinition();
  2086. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2087. }
  2088. return ObjCFastEnumerationStateType;
  2089. }
  2090. llvm::Constant *
  2091. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2092. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2093. // Don't emit it as the address of the string, emit the string data itself
  2094. // as an inline array.
  2095. if (E->getCharByteWidth() == 1) {
  2096. SmallString<64> Str(E->getString());
  2097. // Resize the string to the right size, which is indicated by its type.
  2098. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2099. Str.resize(CAT->getSize().getZExtValue());
  2100. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2101. }
  2102. llvm::ArrayType *AType =
  2103. cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2104. llvm::Type *ElemTy = AType->getElementType();
  2105. unsigned NumElements = AType->getNumElements();
  2106. // Wide strings have either 2-byte or 4-byte elements.
  2107. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2108. SmallVector<uint16_t, 32> Elements;
  2109. Elements.reserve(NumElements);
  2110. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2111. Elements.push_back(E->getCodeUnit(i));
  2112. Elements.resize(NumElements);
  2113. return llvm::ConstantDataArray::get(VMContext, Elements);
  2114. }
  2115. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2116. SmallVector<uint32_t, 32> Elements;
  2117. Elements.reserve(NumElements);
  2118. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2119. Elements.push_back(E->getCodeUnit(i));
  2120. Elements.resize(NumElements);
  2121. return llvm::ConstantDataArray::get(VMContext, Elements);
  2122. }
  2123. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2124. /// constant array for the given string literal.
  2125. llvm::Constant *
  2126. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  2127. CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
  2128. if (S->isAscii() || S->isUTF8()) {
  2129. SmallString<64> Str(S->getString());
  2130. // Resize the string to the right size, which is indicated by its type.
  2131. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
  2132. Str.resize(CAT->getSize().getZExtValue());
  2133. return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
  2134. }
  2135. // FIXME: the following does not memoize wide strings.
  2136. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2137. llvm::GlobalVariable *GV =
  2138. new llvm::GlobalVariable(getModule(),C->getType(),
  2139. !LangOpts.WritableStrings,
  2140. llvm::GlobalValue::PrivateLinkage,
  2141. C,".str");
  2142. GV->setAlignment(Align.getQuantity());
  2143. GV->setUnnamedAddr(true);
  2144. return GV;
  2145. }
  2146. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2147. /// array for the given ObjCEncodeExpr node.
  2148. llvm::Constant *
  2149. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2150. std::string Str;
  2151. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2152. return GetAddrOfConstantCString(Str);
  2153. }
  2154. /// GenerateWritableString -- Creates storage for a string literal.
  2155. static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
  2156. bool constant,
  2157. CodeGenModule &CGM,
  2158. const char *GlobalName,
  2159. unsigned Alignment) {
  2160. // Create Constant for this string literal. Don't add a '\0'.
  2161. llvm::Constant *C =
  2162. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
  2163. // Create a global variable for this string
  2164. llvm::GlobalVariable *GV =
  2165. new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
  2166. llvm::GlobalValue::PrivateLinkage,
  2167. C, GlobalName);
  2168. GV->setAlignment(Alignment);
  2169. GV->setUnnamedAddr(true);
  2170. return GV;
  2171. }
  2172. /// GetAddrOfConstantString - Returns a pointer to a character array
  2173. /// containing the literal. This contents are exactly that of the
  2174. /// given string, i.e. it will not be null terminated automatically;
  2175. /// see GetAddrOfConstantCString. Note that whether the result is
  2176. /// actually a pointer to an LLVM constant depends on
  2177. /// Feature.WriteableStrings.
  2178. ///
  2179. /// The result has pointer to array type.
  2180. llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
  2181. const char *GlobalName,
  2182. unsigned Alignment) {
  2183. // Get the default prefix if a name wasn't specified.
  2184. if (!GlobalName)
  2185. GlobalName = ".str";
  2186. if (Alignment == 0)
  2187. Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
  2188. .getQuantity();
  2189. // Don't share any string literals if strings aren't constant.
  2190. if (LangOpts.WritableStrings)
  2191. return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
  2192. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2193. ConstantStringMap.GetOrCreateValue(Str);
  2194. if (llvm::GlobalVariable *GV = Entry.getValue()) {
  2195. if (Alignment > GV->getAlignment()) {
  2196. GV->setAlignment(Alignment);
  2197. }
  2198. return GV;
  2199. }
  2200. // Create a global variable for this.
  2201. llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
  2202. Alignment);
  2203. Entry.setValue(GV);
  2204. return GV;
  2205. }
  2206. /// GetAddrOfConstantCString - Returns a pointer to a character
  2207. /// array containing the literal and a terminating '\0'
  2208. /// character. The result has pointer to array type.
  2209. llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
  2210. const char *GlobalName,
  2211. unsigned Alignment) {
  2212. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2213. return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
  2214. }
  2215. llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
  2216. const MaterializeTemporaryExpr *E, const Expr *Init) {
  2217. assert((E->getStorageDuration() == SD_Static ||
  2218. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  2219. const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
  2220. // If we're not materializing a subobject of the temporary, keep the
  2221. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  2222. QualType MaterializedType = Init->getType();
  2223. if (Init == E->GetTemporaryExpr())
  2224. MaterializedType = E->getType();
  2225. llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
  2226. if (Slot)
  2227. return Slot;
  2228. // FIXME: If an externally-visible declaration extends multiple temporaries,
  2229. // we need to give each temporary the same name in every translation unit (and
  2230. // we also need to make the temporaries externally-visible).
  2231. SmallString<256> Name;
  2232. llvm::raw_svector_ostream Out(Name);
  2233. getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
  2234. Out.flush();
  2235. APValue *Value = 0;
  2236. if (E->getStorageDuration() == SD_Static) {
  2237. // We might have a cached constant initializer for this temporary. Note
  2238. // that this might have a different value from the value computed by
  2239. // evaluating the initializer if the surrounding constant expression
  2240. // modifies the temporary.
  2241. Value = getContext().getMaterializedTemporaryValue(E, false);
  2242. if (Value && Value->isUninit())
  2243. Value = 0;
  2244. }
  2245. // Try evaluating it now, it might have a constant initializer.
  2246. Expr::EvalResult EvalResult;
  2247. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  2248. !EvalResult.hasSideEffects())
  2249. Value = &EvalResult.Val;
  2250. llvm::Constant *InitialValue = 0;
  2251. bool Constant = false;
  2252. llvm::Type *Type;
  2253. if (Value) {
  2254. // The temporary has a constant initializer, use it.
  2255. InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
  2256. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  2257. Type = InitialValue->getType();
  2258. } else {
  2259. // No initializer, the initialization will be provided when we
  2260. // initialize the declaration which performed lifetime extension.
  2261. Type = getTypes().ConvertTypeForMem(MaterializedType);
  2262. }
  2263. // Create a global variable for this lifetime-extended temporary.
  2264. llvm::GlobalVariable *GV =
  2265. new llvm::GlobalVariable(getModule(), Type, Constant,
  2266. llvm::GlobalValue::PrivateLinkage,
  2267. InitialValue, Name.c_str());
  2268. GV->setAlignment(
  2269. getContext().getTypeAlignInChars(MaterializedType).getQuantity());
  2270. if (VD->getTLSKind())
  2271. setTLSMode(GV, *VD);
  2272. Slot = GV;
  2273. return GV;
  2274. }
  2275. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2276. /// properties for an implementation.
  2277. void CodeGenModule::EmitObjCPropertyImplementations(const
  2278. ObjCImplementationDecl *D) {
  2279. for (ObjCImplementationDecl::propimpl_iterator
  2280. i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
  2281. ObjCPropertyImplDecl *PID = *i;
  2282. // Dynamic is just for type-checking.
  2283. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2284. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2285. // Determine which methods need to be implemented, some may have
  2286. // been overridden. Note that ::isPropertyAccessor is not the method
  2287. // we want, that just indicates if the decl came from a
  2288. // property. What we want to know is if the method is defined in
  2289. // this implementation.
  2290. if (!D->getInstanceMethod(PD->getGetterName()))
  2291. CodeGenFunction(*this).GenerateObjCGetter(
  2292. const_cast<ObjCImplementationDecl *>(D), PID);
  2293. if (!PD->isReadOnly() &&
  2294. !D->getInstanceMethod(PD->getSetterName()))
  2295. CodeGenFunction(*this).GenerateObjCSetter(
  2296. const_cast<ObjCImplementationDecl *>(D), PID);
  2297. }
  2298. }
  2299. }
  2300. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2301. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2302. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2303. ivar; ivar = ivar->getNextIvar())
  2304. if (ivar->getType().isDestructedType())
  2305. return true;
  2306. return false;
  2307. }
  2308. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2309. /// for an implementation.
  2310. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2311. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2312. if (needsDestructMethod(D)) {
  2313. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2314. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2315. ObjCMethodDecl *DTORMethod =
  2316. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2317. cxxSelector, getContext().VoidTy, 0, D,
  2318. /*isInstance=*/true, /*isVariadic=*/false,
  2319. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  2320. /*isDefined=*/false, ObjCMethodDecl::Required);
  2321. D->addInstanceMethod(DTORMethod);
  2322. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2323. D->setHasDestructors(true);
  2324. }
  2325. // If the implementation doesn't have any ivar initializers, we don't need
  2326. // a .cxx_construct.
  2327. if (D->getNumIvarInitializers() == 0)
  2328. return;
  2329. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2330. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2331. // The constructor returns 'self'.
  2332. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2333. D->getLocation(),
  2334. D->getLocation(),
  2335. cxxSelector,
  2336. getContext().getObjCIdType(), 0,
  2337. D, /*isInstance=*/true,
  2338. /*isVariadic=*/false,
  2339. /*isPropertyAccessor=*/true,
  2340. /*isImplicitlyDeclared=*/true,
  2341. /*isDefined=*/false,
  2342. ObjCMethodDecl::Required);
  2343. D->addInstanceMethod(CTORMethod);
  2344. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2345. D->setHasNonZeroConstructors(true);
  2346. }
  2347. /// EmitNamespace - Emit all declarations in a namespace.
  2348. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2349. for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
  2350. I != E; ++I) {
  2351. if (const VarDecl *VD = dyn_cast<VarDecl>(*I))
  2352. if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
  2353. VD->getTemplateSpecializationKind() != TSK_Undeclared)
  2354. continue;
  2355. EmitTopLevelDecl(*I);
  2356. }
  2357. }
  2358. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2359. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2360. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2361. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2362. ErrorUnsupported(LSD, "linkage spec");
  2363. return;
  2364. }
  2365. for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
  2366. I != E; ++I) {
  2367. // Meta-data for ObjC class includes references to implemented methods.
  2368. // Generate class's method definitions first.
  2369. if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
  2370. for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
  2371. MEnd = OID->meth_end();
  2372. M != MEnd; ++M)
  2373. EmitTopLevelDecl(*M);
  2374. }
  2375. EmitTopLevelDecl(*I);
  2376. }
  2377. }
  2378. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2379. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2380. // Ignore dependent declarations.
  2381. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2382. return;
  2383. switch (D->getKind()) {
  2384. case Decl::CXXConversion:
  2385. case Decl::CXXMethod:
  2386. case Decl::Function:
  2387. // Skip function templates
  2388. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2389. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2390. return;
  2391. EmitGlobal(cast<FunctionDecl>(D));
  2392. break;
  2393. case Decl::Var:
  2394. // Skip variable templates
  2395. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  2396. return;
  2397. case Decl::VarTemplateSpecialization:
  2398. EmitGlobal(cast<VarDecl>(D));
  2399. break;
  2400. // Indirect fields from global anonymous structs and unions can be
  2401. // ignored; only the actual variable requires IR gen support.
  2402. case Decl::IndirectField:
  2403. break;
  2404. // C++ Decls
  2405. case Decl::Namespace:
  2406. EmitNamespace(cast<NamespaceDecl>(D));
  2407. break;
  2408. // No code generation needed.
  2409. case Decl::UsingShadow:
  2410. case Decl::Using:
  2411. case Decl::ClassTemplate:
  2412. case Decl::VarTemplate:
  2413. case Decl::VarTemplatePartialSpecialization:
  2414. case Decl::FunctionTemplate:
  2415. case Decl::TypeAliasTemplate:
  2416. case Decl::Block:
  2417. case Decl::Empty:
  2418. break;
  2419. case Decl::NamespaceAlias:
  2420. if (CGDebugInfo *DI = getModuleDebugInfo())
  2421. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  2422. return;
  2423. case Decl::UsingDirective: // using namespace X; [C++]
  2424. if (CGDebugInfo *DI = getModuleDebugInfo())
  2425. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  2426. return;
  2427. case Decl::CXXConstructor:
  2428. // Skip function templates
  2429. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2430. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2431. return;
  2432. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2433. break;
  2434. case Decl::CXXDestructor:
  2435. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2436. return;
  2437. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2438. break;
  2439. case Decl::StaticAssert:
  2440. // Nothing to do.
  2441. break;
  2442. // Objective-C Decls
  2443. // Forward declarations, no (immediate) code generation.
  2444. case Decl::ObjCInterface:
  2445. case Decl::ObjCCategory:
  2446. break;
  2447. case Decl::ObjCProtocol: {
  2448. ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
  2449. if (Proto->isThisDeclarationADefinition())
  2450. ObjCRuntime->GenerateProtocol(Proto);
  2451. break;
  2452. }
  2453. case Decl::ObjCCategoryImpl:
  2454. // Categories have properties but don't support synthesize so we
  2455. // can ignore them here.
  2456. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2457. break;
  2458. case Decl::ObjCImplementation: {
  2459. ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
  2460. EmitObjCPropertyImplementations(OMD);
  2461. EmitObjCIvarInitializations(OMD);
  2462. ObjCRuntime->GenerateClass(OMD);
  2463. // Emit global variable debug information.
  2464. if (CGDebugInfo *DI = getModuleDebugInfo())
  2465. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  2466. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  2467. OMD->getClassInterface()), OMD->getLocation());
  2468. break;
  2469. }
  2470. case Decl::ObjCMethod: {
  2471. ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
  2472. // If this is not a prototype, emit the body.
  2473. if (OMD->getBody())
  2474. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2475. break;
  2476. }
  2477. case Decl::ObjCCompatibleAlias:
  2478. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2479. break;
  2480. case Decl::LinkageSpec:
  2481. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2482. break;
  2483. case Decl::FileScopeAsm: {
  2484. FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
  2485. StringRef AsmString = AD->getAsmString()->getString();
  2486. const std::string &S = getModule().getModuleInlineAsm();
  2487. if (S.empty())
  2488. getModule().setModuleInlineAsm(AsmString);
  2489. else if (S.end()[-1] == '\n')
  2490. getModule().setModuleInlineAsm(S + AsmString.str());
  2491. else
  2492. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  2493. break;
  2494. }
  2495. case Decl::Import: {
  2496. ImportDecl *Import = cast<ImportDecl>(D);
  2497. // Ignore import declarations that come from imported modules.
  2498. if (clang::Module *Owner = Import->getOwningModule()) {
  2499. if (getLangOpts().CurrentModule.empty() ||
  2500. Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
  2501. break;
  2502. }
  2503. ImportedModules.insert(Import->getImportedModule());
  2504. break;
  2505. }
  2506. default:
  2507. // Make sure we handled everything we should, every other kind is a
  2508. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  2509. // function. Need to recode Decl::Kind to do that easily.
  2510. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  2511. }
  2512. }
  2513. /// Turns the given pointer into a constant.
  2514. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  2515. const void *Ptr) {
  2516. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  2517. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  2518. return llvm::ConstantInt::get(i64, PtrInt);
  2519. }
  2520. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  2521. llvm::NamedMDNode *&GlobalMetadata,
  2522. GlobalDecl D,
  2523. llvm::GlobalValue *Addr) {
  2524. if (!GlobalMetadata)
  2525. GlobalMetadata =
  2526. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  2527. // TODO: should we report variant information for ctors/dtors?
  2528. llvm::Value *Ops[] = {
  2529. Addr,
  2530. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  2531. };
  2532. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2533. }
  2534. /// For each function which is declared within an extern "C" region and marked
  2535. /// as 'used', but has internal linkage, create an alias from the unmangled
  2536. /// name to the mangled name if possible. People expect to be able to refer
  2537. /// to such functions with an unmangled name from inline assembly within the
  2538. /// same translation unit.
  2539. void CodeGenModule::EmitStaticExternCAliases() {
  2540. for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
  2541. E = StaticExternCValues.end();
  2542. I != E; ++I) {
  2543. IdentifierInfo *Name = I->first;
  2544. llvm::GlobalValue *Val = I->second;
  2545. if (Val && !getModule().getNamedValue(Name->getName()))
  2546. AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
  2547. Name->getName(), Val, &getModule()));
  2548. }
  2549. }
  2550. /// Emits metadata nodes associating all the global values in the
  2551. /// current module with the Decls they came from. This is useful for
  2552. /// projects using IR gen as a subroutine.
  2553. ///
  2554. /// Since there's currently no way to associate an MDNode directly
  2555. /// with an llvm::GlobalValue, we create a global named metadata
  2556. /// with the name 'clang.global.decl.ptrs'.
  2557. void CodeGenModule::EmitDeclMetadata() {
  2558. llvm::NamedMDNode *GlobalMetadata = 0;
  2559. // StaticLocalDeclMap
  2560. for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
  2561. I = MangledDeclNames.begin(), E = MangledDeclNames.end();
  2562. I != E; ++I) {
  2563. llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
  2564. EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
  2565. }
  2566. }
  2567. /// Emits metadata nodes for all the local variables in the current
  2568. /// function.
  2569. void CodeGenFunction::EmitDeclMetadata() {
  2570. if (LocalDeclMap.empty()) return;
  2571. llvm::LLVMContext &Context = getLLVMContext();
  2572. // Find the unique metadata ID for this name.
  2573. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  2574. llvm::NamedMDNode *GlobalMetadata = 0;
  2575. for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
  2576. I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
  2577. const Decl *D = I->first;
  2578. llvm::Value *Addr = I->second;
  2579. if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  2580. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  2581. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
  2582. } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  2583. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  2584. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  2585. }
  2586. }
  2587. }
  2588. void CodeGenModule::EmitVersionIdentMetadata() {
  2589. llvm::NamedMDNode *IdentMetadata =
  2590. TheModule.getOrInsertNamedMetadata("llvm.ident");
  2591. std::string Version = getClangFullVersion();
  2592. llvm::LLVMContext &Ctx = TheModule.getContext();
  2593. llvm::Value *IdentNode[] = {
  2594. llvm::MDString::get(Ctx, Version)
  2595. };
  2596. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  2597. }
  2598. void CodeGenModule::EmitCoverageFile() {
  2599. if (!getCodeGenOpts().CoverageFile.empty()) {
  2600. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  2601. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  2602. llvm::LLVMContext &Ctx = TheModule.getContext();
  2603. llvm::MDString *CoverageFile =
  2604. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  2605. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  2606. llvm::MDNode *CU = CUNode->getOperand(i);
  2607. llvm::Value *node[] = { CoverageFile, CU };
  2608. llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
  2609. GCov->addOperand(N);
  2610. }
  2611. }
  2612. }
  2613. }
  2614. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
  2615. QualType GuidType) {
  2616. // Sema has checked that all uuid strings are of the form
  2617. // "12345678-1234-1234-1234-1234567890ab".
  2618. assert(Uuid.size() == 36);
  2619. for (unsigned i = 0; i < 36; ++i) {
  2620. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  2621. else assert(isHexDigit(Uuid[i]));
  2622. }
  2623. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  2624. llvm::Constant *Field3[8];
  2625. for (unsigned Idx = 0; Idx < 8; ++Idx)
  2626. Field3[Idx] = llvm::ConstantInt::get(
  2627. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  2628. llvm::Constant *Fields[4] = {
  2629. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  2630. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  2631. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  2632. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  2633. };
  2634. return llvm::ConstantStruct::getAnon(Fields);
  2635. }