CodeGenModule.cpp 128 KB

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