CodeGenModule.cpp 187 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994
  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 "CGBlocks.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGCall.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGObjCRuntime.h"
  20. #include "CGOpenCLRuntime.h"
  21. #include "CGOpenMPRuntime.h"
  22. #include "CGOpenMPRuntimeNVPTX.h"
  23. #include "CodeGenFunction.h"
  24. #include "CodeGenPGO.h"
  25. #include "ConstantEmitter.h"
  26. #include "CoverageMappingGen.h"
  27. #include "TargetInfo.h"
  28. #include "clang/AST/ASTContext.h"
  29. #include "clang/AST/CharUnits.h"
  30. #include "clang/AST/DeclCXX.h"
  31. #include "clang/AST/DeclObjC.h"
  32. #include "clang/AST/DeclTemplate.h"
  33. #include "clang/AST/Mangle.h"
  34. #include "clang/AST/RecordLayout.h"
  35. #include "clang/AST/RecursiveASTVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/Diagnostic.h"
  39. #include "clang/Basic/Module.h"
  40. #include "clang/Basic/SourceManager.h"
  41. #include "clang/Basic/TargetInfo.h"
  42. #include "clang/Basic/Version.h"
  43. #include "clang/CodeGen/ConstantInitBuilder.h"
  44. #include "clang/Frontend/CodeGenOptions.h"
  45. #include "clang/Sema/SemaDiagnostic.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include "llvm/Analysis/TargetLibraryInfo.h"
  48. #include "llvm/IR/CallSite.h"
  49. #include "llvm/IR/CallingConv.h"
  50. #include "llvm/IR/DataLayout.h"
  51. #include "llvm/IR/Intrinsics.h"
  52. #include "llvm/IR/LLVMContext.h"
  53. #include "llvm/IR/Module.h"
  54. #include "llvm/ProfileData/InstrProfReader.h"
  55. #include "llvm/Support/ConvertUTF.h"
  56. #include "llvm/Support/ErrorHandling.h"
  57. #include "llvm/Support/MD5.h"
  58. using namespace clang;
  59. using namespace CodeGen;
  60. static llvm::cl::opt<bool> LimitedCoverage(
  61. "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
  62. llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
  63. llvm::cl::init(false));
  64. static const char AnnotationSection[] = "llvm.metadata";
  65. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  66. switch (CGM.getTarget().getCXXABI().getKind()) {
  67. case TargetCXXABI::GenericAArch64:
  68. case TargetCXXABI::GenericARM:
  69. case TargetCXXABI::iOS:
  70. case TargetCXXABI::iOS64:
  71. case TargetCXXABI::WatchOS:
  72. case TargetCXXABI::GenericMIPS:
  73. case TargetCXXABI::GenericItanium:
  74. case TargetCXXABI::WebAssembly:
  75. return CreateItaniumCXXABI(CGM);
  76. case TargetCXXABI::Microsoft:
  77. return CreateMicrosoftCXXABI(CGM);
  78. }
  79. llvm_unreachable("invalid C++ ABI kind");
  80. }
  81. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  82. const PreprocessorOptions &PPO,
  83. const CodeGenOptions &CGO, llvm::Module &M,
  84. DiagnosticsEngine &diags,
  85. CoverageSourceInfo *CoverageInfo)
  86. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  87. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  88. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  89. VMContext(M.getContext()), Types(*this), VTables(*this),
  90. SanitizerMD(new SanitizerMetadata(*this)) {
  91. // Initialize the type cache.
  92. llvm::LLVMContext &LLVMContext = M.getContext();
  93. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  94. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  95. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  96. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  97. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  98. HalfTy = llvm::Type::getHalfTy(LLVMContext);
  99. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  100. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  101. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  102. PointerAlignInBytes =
  103. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  104. SizeSizeInBytes =
  105. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  106. IntAlignInBytes =
  107. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  108. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  109. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  110. C.getTargetInfo().getMaxPointerWidth());
  111. Int8PtrTy = Int8Ty->getPointerTo(0);
  112. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  113. AllocaInt8PtrTy = Int8Ty->getPointerTo(
  114. M.getDataLayout().getAllocaAddrSpace());
  115. ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
  116. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  117. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  118. if (LangOpts.ObjC1)
  119. createObjCRuntime();
  120. if (LangOpts.OpenCL)
  121. createOpenCLRuntime();
  122. if (LangOpts.OpenMP)
  123. createOpenMPRuntime();
  124. if (LangOpts.CUDA)
  125. createCUDARuntime();
  126. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  127. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  128. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  129. TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
  130. getCXXABI().getMangleContext()));
  131. // If debug info or coverage generation is enabled, create the CGDebugInfo
  132. // object.
  133. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  134. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  135. DebugInfo.reset(new CGDebugInfo(*this));
  136. Block.GlobalUniqueCount = 0;
  137. if (C.getLangOpts().ObjC1)
  138. ObjCData.reset(new ObjCEntrypoints());
  139. if (CodeGenOpts.hasProfileClangUse()) {
  140. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  141. CodeGenOpts.ProfileInstrumentUsePath);
  142. if (auto E = ReaderOrErr.takeError()) {
  143. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  144. "Could not read profile %0: %1");
  145. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  146. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  147. << EI.message();
  148. });
  149. } else
  150. PGOReader = std::move(ReaderOrErr.get());
  151. }
  152. // If coverage mapping generation is enabled, create the
  153. // CoverageMappingModuleGen object.
  154. if (CodeGenOpts.CoverageMapping)
  155. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  156. }
  157. CodeGenModule::~CodeGenModule() {}
  158. void CodeGenModule::createObjCRuntime() {
  159. // This is just isGNUFamily(), but we want to force implementors of
  160. // new ABIs to decide how best to do this.
  161. switch (LangOpts.ObjCRuntime.getKind()) {
  162. case ObjCRuntime::GNUstep:
  163. case ObjCRuntime::GCC:
  164. case ObjCRuntime::ObjFW:
  165. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  166. return;
  167. case ObjCRuntime::FragileMacOSX:
  168. case ObjCRuntime::MacOSX:
  169. case ObjCRuntime::iOS:
  170. case ObjCRuntime::WatchOS:
  171. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  172. return;
  173. }
  174. llvm_unreachable("bad runtime kind");
  175. }
  176. void CodeGenModule::createOpenCLRuntime() {
  177. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  178. }
  179. void CodeGenModule::createOpenMPRuntime() {
  180. // Select a specialized code generation class based on the target, if any.
  181. // If it does not exist use the default implementation.
  182. switch (getTriple().getArch()) {
  183. case llvm::Triple::nvptx:
  184. case llvm::Triple::nvptx64:
  185. assert(getLangOpts().OpenMPIsDevice &&
  186. "OpenMP NVPTX is only prepared to deal with device code.");
  187. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  188. break;
  189. default:
  190. if (LangOpts.OpenMPSimd)
  191. OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
  192. else
  193. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  194. break;
  195. }
  196. }
  197. void CodeGenModule::createCUDARuntime() {
  198. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  199. }
  200. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  201. Replacements[Name] = C;
  202. }
  203. void CodeGenModule::applyReplacements() {
  204. for (auto &I : Replacements) {
  205. StringRef MangledName = I.first();
  206. llvm::Constant *Replacement = I.second;
  207. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  208. if (!Entry)
  209. continue;
  210. auto *OldF = cast<llvm::Function>(Entry);
  211. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  212. if (!NewF) {
  213. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  214. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  215. } else {
  216. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  217. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  218. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  219. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  220. }
  221. }
  222. // Replace old with new, but keep the old order.
  223. OldF->replaceAllUsesWith(Replacement);
  224. if (NewF) {
  225. NewF->removeFromParent();
  226. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  227. NewF);
  228. }
  229. OldF->eraseFromParent();
  230. }
  231. }
  232. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  233. GlobalValReplacements.push_back(std::make_pair(GV, C));
  234. }
  235. void CodeGenModule::applyGlobalValReplacements() {
  236. for (auto &I : GlobalValReplacements) {
  237. llvm::GlobalValue *GV = I.first;
  238. llvm::Constant *C = I.second;
  239. GV->replaceAllUsesWith(C);
  240. GV->eraseFromParent();
  241. }
  242. }
  243. // This is only used in aliases that we created and we know they have a
  244. // linear structure.
  245. static const llvm::GlobalObject *getAliasedGlobal(
  246. const llvm::GlobalIndirectSymbol &GIS) {
  247. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  248. const llvm::Constant *C = &GIS;
  249. for (;;) {
  250. C = C->stripPointerCasts();
  251. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  252. return GO;
  253. // stripPointerCasts will not walk over weak aliases.
  254. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  255. if (!GIS2)
  256. return nullptr;
  257. if (!Visited.insert(GIS2).second)
  258. return nullptr;
  259. C = GIS2->getIndirectSymbol();
  260. }
  261. }
  262. void CodeGenModule::checkAliases() {
  263. // Check if the constructed aliases are well formed. It is really unfortunate
  264. // that we have to do this in CodeGen, but we only construct mangled names
  265. // and aliases during codegen.
  266. bool Error = false;
  267. DiagnosticsEngine &Diags = getDiags();
  268. for (const GlobalDecl &GD : Aliases) {
  269. const auto *D = cast<ValueDecl>(GD.getDecl());
  270. SourceLocation Location;
  271. bool IsIFunc = D->hasAttr<IFuncAttr>();
  272. if (const Attr *A = D->getDefiningAttr())
  273. Location = A->getLocation();
  274. else
  275. llvm_unreachable("Not an alias or ifunc?");
  276. StringRef MangledName = getMangledName(GD);
  277. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  278. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  279. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  280. if (!GV) {
  281. Error = true;
  282. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  283. } else if (GV->isDeclaration()) {
  284. Error = true;
  285. Diags.Report(Location, diag::err_alias_to_undefined)
  286. << IsIFunc << IsIFunc;
  287. } else if (IsIFunc) {
  288. // Check resolver function type.
  289. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  290. GV->getType()->getPointerElementType());
  291. assert(FTy);
  292. if (!FTy->getReturnType()->isPointerTy())
  293. Diags.Report(Location, diag::err_ifunc_resolver_return);
  294. if (FTy->getNumParams())
  295. Diags.Report(Location, diag::err_ifunc_resolver_params);
  296. }
  297. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  298. llvm::GlobalValue *AliaseeGV;
  299. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  300. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  301. else
  302. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  303. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  304. StringRef AliasSection = SA->getName();
  305. if (AliasSection != AliaseeGV->getSection())
  306. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  307. << AliasSection << IsIFunc << IsIFunc;
  308. }
  309. // We have to handle alias to weak aliases in here. LLVM itself disallows
  310. // this since the object semantics would not match the IL one. For
  311. // compatibility with gcc we implement it by just pointing the alias
  312. // to its aliasee's aliasee. We also warn, since the user is probably
  313. // expecting the link to be weak.
  314. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  315. if (GA->isInterposable()) {
  316. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  317. << GV->getName() << GA->getName() << IsIFunc;
  318. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  319. GA->getIndirectSymbol(), Alias->getType());
  320. Alias->setIndirectSymbol(Aliasee);
  321. }
  322. }
  323. }
  324. if (!Error)
  325. return;
  326. for (const GlobalDecl &GD : Aliases) {
  327. StringRef MangledName = getMangledName(GD);
  328. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  329. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  330. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  331. Alias->eraseFromParent();
  332. }
  333. }
  334. void CodeGenModule::clear() {
  335. DeferredDeclsToEmit.clear();
  336. if (OpenMPRuntime)
  337. OpenMPRuntime->clear();
  338. }
  339. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  340. StringRef MainFile) {
  341. if (!hasDiagnostics())
  342. return;
  343. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  344. if (MainFile.empty())
  345. MainFile = "<stdin>";
  346. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  347. } else {
  348. if (Mismatched > 0)
  349. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
  350. if (Missing > 0)
  351. Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
  352. }
  353. }
  354. void CodeGenModule::Release() {
  355. EmitDeferred();
  356. EmitVTablesOpportunistically();
  357. applyGlobalValReplacements();
  358. applyReplacements();
  359. checkAliases();
  360. emitMultiVersionFunctions();
  361. EmitCXXGlobalInitFunc();
  362. EmitCXXGlobalDtorFunc();
  363. EmitCXXThreadLocalInitFunc();
  364. if (ObjCRuntime)
  365. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  366. AddGlobalCtor(ObjCInitFunction);
  367. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  368. CUDARuntime) {
  369. if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
  370. AddGlobalCtor(CudaCtorFunction);
  371. if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
  372. AddGlobalDtor(CudaDtorFunction);
  373. }
  374. if (OpenMPRuntime)
  375. if (llvm::Function *OpenMPRegistrationFunction =
  376. OpenMPRuntime->emitRegistrationFunction()) {
  377. auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
  378. OpenMPRegistrationFunction : nullptr;
  379. AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
  380. }
  381. if (PGOReader) {
  382. getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
  383. if (PGOStats.hasDiagnostics())
  384. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  385. }
  386. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  387. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  388. EmitGlobalAnnotations();
  389. EmitStaticExternCAliases();
  390. EmitDeferredUnusedCoverageMappings();
  391. if (CoverageMapping)
  392. CoverageMapping->emit();
  393. if (CodeGenOpts.SanitizeCfiCrossDso) {
  394. CodeGenFunction(*this).EmitCfiCheckFail();
  395. CodeGenFunction(*this).EmitCfiCheckStub();
  396. }
  397. emitAtAvailableLinkGuard();
  398. emitLLVMUsed();
  399. if (SanStats)
  400. SanStats->finish();
  401. if (CodeGenOpts.Autolink &&
  402. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  403. EmitModuleLinkOptions();
  404. }
  405. // Record mregparm value now so it is visible through rest of codegen.
  406. if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  407. getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
  408. CodeGenOpts.NumRegisterParameters);
  409. if (CodeGenOpts.DwarfVersion) {
  410. // We actually want the latest version when there are conflicts.
  411. // We can change from Warning to Latest if such mode is supported.
  412. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  413. CodeGenOpts.DwarfVersion);
  414. }
  415. if (CodeGenOpts.EmitCodeView) {
  416. // Indicate that we want CodeView in the metadata.
  417. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  418. }
  419. if (CodeGenOpts.ControlFlowGuard) {
  420. // We want function ID tables for Control Flow Guard.
  421. getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
  422. }
  423. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  424. // We don't support LTO with 2 with different StrictVTablePointers
  425. // FIXME: we could support it by stripping all the information introduced
  426. // by StrictVTablePointers.
  427. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  428. llvm::Metadata *Ops[2] = {
  429. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  430. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  431. llvm::Type::getInt32Ty(VMContext), 1))};
  432. getModule().addModuleFlag(llvm::Module::Require,
  433. "StrictVTablePointersRequirement",
  434. llvm::MDNode::get(VMContext, Ops));
  435. }
  436. if (DebugInfo)
  437. // We support a single version in the linked module. The LLVM
  438. // parser will drop debug info with a different version number
  439. // (and warn about it, too).
  440. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  441. llvm::DEBUG_METADATA_VERSION);
  442. // We need to record the widths of enums and wchar_t, so that we can generate
  443. // the correct build attributes in the ARM backend. wchar_size is also used by
  444. // TargetLibraryInfo.
  445. uint64_t WCharWidth =
  446. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  447. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  448. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  449. if ( Arch == llvm::Triple::arm
  450. || Arch == llvm::Triple::armeb
  451. || Arch == llvm::Triple::thumb
  452. || Arch == llvm::Triple::thumbeb) {
  453. // The minimum width of an enum in bytes
  454. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  455. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  456. }
  457. if (CodeGenOpts.SanitizeCfiCrossDso) {
  458. // Indicate that we want cross-DSO control flow integrity checks.
  459. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  460. }
  461. if (CodeGenOpts.CFProtectionReturn &&
  462. Target.checkCFProtectionReturnSupported(getDiags())) {
  463. // Indicate that we want to instrument return control flow protection.
  464. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
  465. 1);
  466. }
  467. if (CodeGenOpts.CFProtectionBranch &&
  468. Target.checkCFProtectionBranchSupported(getDiags())) {
  469. // Indicate that we want to instrument branch control flow protection.
  470. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
  471. 1);
  472. }
  473. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  474. // Indicate whether __nvvm_reflect should be configured to flush denormal
  475. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  476. // property.)
  477. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  478. LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
  479. }
  480. // Emit OpenCL specific module metadata: OpenCL/SPIR version.
  481. if (LangOpts.OpenCL) {
  482. EmitOpenCLMetadata();
  483. // Emit SPIR version.
  484. if (getTriple().getArch() == llvm::Triple::spir ||
  485. getTriple().getArch() == llvm::Triple::spir64) {
  486. // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
  487. // opencl.spir.version named metadata.
  488. llvm::Metadata *SPIRVerElts[] = {
  489. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  490. Int32Ty, LangOpts.OpenCLVersion / 100)),
  491. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  492. Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
  493. llvm::NamedMDNode *SPIRVerMD =
  494. TheModule.getOrInsertNamedMetadata("opencl.spir.version");
  495. llvm::LLVMContext &Ctx = TheModule.getContext();
  496. SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
  497. }
  498. }
  499. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  500. assert(PLevel < 3 && "Invalid PIC Level");
  501. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  502. if (Context.getLangOpts().PIE)
  503. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  504. }
  505. if (CodeGenOpts.NoPLT)
  506. getModule().setRtLibUseGOT();
  507. SimplifyPersonality();
  508. if (getCodeGenOpts().EmitDeclMetadata)
  509. EmitDeclMetadata();
  510. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  511. EmitCoverageFile();
  512. if (DebugInfo)
  513. DebugInfo->finalize();
  514. EmitVersionIdentMetadata();
  515. EmitTargetMetadata();
  516. }
  517. void CodeGenModule::EmitOpenCLMetadata() {
  518. // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
  519. // opencl.ocl.version named metadata node.
  520. llvm::Metadata *OCLVerElts[] = {
  521. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  522. Int32Ty, LangOpts.OpenCLVersion / 100)),
  523. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  524. Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
  525. llvm::NamedMDNode *OCLVerMD =
  526. TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
  527. llvm::LLVMContext &Ctx = TheModule.getContext();
  528. OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
  529. }
  530. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  531. // Make sure that this type is translated.
  532. Types.UpdateCompletedType(TD);
  533. }
  534. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  535. // Make sure that this type is translated.
  536. Types.RefreshTypeCacheForClass(RD);
  537. }
  538. llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
  539. if (!TBAA)
  540. return nullptr;
  541. return TBAA->getTypeInfo(QTy);
  542. }
  543. TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
  544. if (!TBAA)
  545. return TBAAAccessInfo();
  546. return TBAA->getAccessInfo(AccessType);
  547. }
  548. TBAAAccessInfo
  549. CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
  550. if (!TBAA)
  551. return TBAAAccessInfo();
  552. return TBAA->getVTablePtrAccessInfo(VTablePtrType);
  553. }
  554. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  555. if (!TBAA)
  556. return nullptr;
  557. return TBAA->getTBAAStructInfo(QTy);
  558. }
  559. llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
  560. if (!TBAA)
  561. return nullptr;
  562. return TBAA->getBaseTypeInfo(QTy);
  563. }
  564. llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
  565. if (!TBAA)
  566. return nullptr;
  567. return TBAA->getAccessTagInfo(Info);
  568. }
  569. TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  570. TBAAAccessInfo TargetInfo) {
  571. if (!TBAA)
  572. return TBAAAccessInfo();
  573. return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
  574. }
  575. TBAAAccessInfo
  576. CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
  577. TBAAAccessInfo InfoB) {
  578. if (!TBAA)
  579. return TBAAAccessInfo();
  580. return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
  581. }
  582. TBAAAccessInfo
  583. CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
  584. TBAAAccessInfo SrcInfo) {
  585. if (!TBAA)
  586. return TBAAAccessInfo();
  587. return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
  588. }
  589. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  590. TBAAAccessInfo TBAAInfo) {
  591. if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
  592. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
  593. }
  594. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  595. llvm::Instruction *I, const CXXRecordDecl *RD) {
  596. I->setMetadata(llvm::LLVMContext::MD_invariant_group,
  597. llvm::MDNode::get(getLLVMContext(), {}));
  598. }
  599. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  600. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  601. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  602. }
  603. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  604. /// specified stmt yet.
  605. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  606. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  607. "cannot compile this %0 yet");
  608. std::string Msg = Type;
  609. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  610. << Msg << S->getSourceRange();
  611. }
  612. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  613. /// specified decl yet.
  614. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  615. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  616. "cannot compile this %0 yet");
  617. std::string Msg = Type;
  618. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  619. }
  620. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  621. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  622. }
  623. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  624. const NamedDecl *D) const {
  625. if (GV->hasDLLImportStorageClass())
  626. return;
  627. // Internal definitions always have default visibility.
  628. if (GV->hasLocalLinkage()) {
  629. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  630. return;
  631. }
  632. // Set visibility for definitions.
  633. LinkageInfo LV = D->getLinkageAndVisibility();
  634. if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
  635. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  636. }
  637. static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
  638. llvm::GlobalValue *GV) {
  639. // DLLImport explicitly marks the GV as external.
  640. if (GV->hasDLLImportStorageClass())
  641. return false;
  642. const llvm::Triple &TT = CGM.getTriple();
  643. // Every other GV is local on COFF.
  644. // Make an exception for windows OS in the triple: Some firmware builds use
  645. // *-win32-macho triples. This (accidentally?) produced windows relocations
  646. // without GOT tables in older clang versions; Keep this behaviour.
  647. // FIXME: even thread local variables?
  648. if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
  649. return true;
  650. // Only handle COFF and ELF for now.
  651. if (!TT.isOSBinFormatELF())
  652. return false;
  653. // If this is not an executable, don't assume anything is local.
  654. const auto &CGOpts = CGM.getCodeGenOpts();
  655. llvm::Reloc::Model RM = CGOpts.RelocationModel;
  656. const auto &LOpts = CGM.getLangOpts();
  657. if (RM != llvm::Reloc::Static && !LOpts.PIE)
  658. return false;
  659. // A definition cannot be preempted from an executable.
  660. if (!GV->isDeclarationForLinker())
  661. return true;
  662. // Most PIC code sequences that assume that a symbol is local cannot produce a
  663. // 0 if it turns out the symbol is undefined. While this is ABI and relocation
  664. // depended, it seems worth it to handle it here.
  665. if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
  666. return false;
  667. // PPC has no copy relocations and cannot use a plt entry as a symbol address.
  668. llvm::Triple::ArchType Arch = TT.getArch();
  669. if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  670. Arch == llvm::Triple::ppc64le)
  671. return false;
  672. // If we can use copy relocations we can assume it is local.
  673. if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
  674. if (!Var->isThreadLocal() &&
  675. (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
  676. return true;
  677. // If we can use a plt entry as the symbol address we can assume it
  678. // is local.
  679. // FIXME: This should work for PIE, but the gold linker doesn't support it.
  680. if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
  681. return true;
  682. // Otherwise don't assue it is local.
  683. return false;
  684. }
  685. void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
  686. if (shouldAssumeDSOLocal(*this, GV))
  687. GV->setDSOLocal(true);
  688. }
  689. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  690. GlobalDecl GD) const {
  691. const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
  692. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
  693. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  694. // Don't dllexport/import destructor thunks.
  695. GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  696. return;
  697. }
  698. }
  699. setDLLImportDLLExport(GV, D);
  700. }
  701. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  702. const NamedDecl *D) const {
  703. if (D->isExternallyVisible()) {
  704. if (D->hasAttr<DLLImportAttr>())
  705. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  706. else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
  707. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  708. }
  709. }
  710. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  711. GlobalDecl GD) const {
  712. setDLLImportDLLExport(GV, GD);
  713. setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
  714. }
  715. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  716. const NamedDecl *D) const {
  717. setDLLImportDLLExport(GV, D);
  718. setGlobalVisibilityAndLocal(GV, D);
  719. }
  720. void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
  721. const NamedDecl *D) const {
  722. setGlobalVisibility(GV, D);
  723. setDSOLocal(GV);
  724. }
  725. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  726. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  727. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  728. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  729. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  730. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  731. }
  732. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  733. CodeGenOptions::TLSModel M) {
  734. switch (M) {
  735. case CodeGenOptions::GeneralDynamicTLSModel:
  736. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  737. case CodeGenOptions::LocalDynamicTLSModel:
  738. return llvm::GlobalVariable::LocalDynamicTLSModel;
  739. case CodeGenOptions::InitialExecTLSModel:
  740. return llvm::GlobalVariable::InitialExecTLSModel;
  741. case CodeGenOptions::LocalExecTLSModel:
  742. return llvm::GlobalVariable::LocalExecTLSModel;
  743. }
  744. llvm_unreachable("Invalid TLS model!");
  745. }
  746. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  747. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  748. llvm::GlobalValue::ThreadLocalMode TLM;
  749. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  750. // Override the TLS model if it is explicitly specified.
  751. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  752. TLM = GetLLVMTLSModel(Attr->getModel());
  753. }
  754. GV->setThreadLocalMode(TLM);
  755. }
  756. static void AppendTargetMangling(const CodeGenModule &CGM,
  757. const TargetAttr *Attr, raw_ostream &Out) {
  758. if (Attr->isDefaultVersion())
  759. return;
  760. Out << '.';
  761. const auto &Target = CGM.getTarget();
  762. TargetAttr::ParsedTargetAttr Info =
  763. Attr->parse([&Target](StringRef LHS, StringRef RHS) {
  764. // Multiversioning doesn't allow "no-${feature}", so we can
  765. // only have "+" prefixes here.
  766. assert(LHS.startswith("+") && RHS.startswith("+") &&
  767. "Features should always have a prefix.");
  768. return Target.multiVersionSortPriority(LHS.substr(1)) >
  769. Target.multiVersionSortPriority(RHS.substr(1));
  770. });
  771. bool IsFirst = true;
  772. if (!Info.Architecture.empty()) {
  773. IsFirst = false;
  774. Out << "arch_" << Info.Architecture;
  775. }
  776. for (StringRef Feat : Info.Features) {
  777. if (!IsFirst)
  778. Out << '_';
  779. IsFirst = false;
  780. Out << Feat.substr(1);
  781. }
  782. }
  783. static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
  784. const NamedDecl *ND,
  785. bool OmitTargetMangling = false) {
  786. SmallString<256> Buffer;
  787. llvm::raw_svector_ostream Out(Buffer);
  788. MangleContext &MC = CGM.getCXXABI().getMangleContext();
  789. if (MC.shouldMangleDeclName(ND)) {
  790. llvm::raw_svector_ostream Out(Buffer);
  791. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  792. MC.mangleCXXCtor(D, GD.getCtorType(), Out);
  793. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  794. MC.mangleCXXDtor(D, GD.getDtorType(), Out);
  795. else
  796. MC.mangleName(ND, Out);
  797. } else {
  798. IdentifierInfo *II = ND->getIdentifier();
  799. assert(II && "Attempt to mangle unnamed decl.");
  800. const auto *FD = dyn_cast<FunctionDecl>(ND);
  801. if (FD &&
  802. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  803. llvm::raw_svector_ostream Out(Buffer);
  804. Out << "__regcall3__" << II->getName();
  805. } else {
  806. Out << II->getName();
  807. }
  808. }
  809. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  810. if (FD->isMultiVersion() && !OmitTargetMangling)
  811. AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
  812. return Out.str();
  813. }
  814. void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
  815. const FunctionDecl *FD) {
  816. if (!FD->isMultiVersion())
  817. return;
  818. // Get the name of what this would be without the 'target' attribute. This
  819. // allows us to lookup the version that was emitted when this wasn't a
  820. // multiversion function.
  821. std::string NonTargetName =
  822. getMangledNameImpl(*this, GD, FD, /*OmitTargetMangling=*/true);
  823. GlobalDecl OtherGD;
  824. if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
  825. assert(OtherGD.getCanonicalDecl()
  826. .getDecl()
  827. ->getAsFunction()
  828. ->isMultiVersion() &&
  829. "Other GD should now be a multiversioned function");
  830. // OtherFD is the version of this function that was mangled BEFORE
  831. // becoming a MultiVersion function. It potentially needs to be updated.
  832. const FunctionDecl *OtherFD =
  833. OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
  834. std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
  835. // This is so that if the initial version was already the 'default'
  836. // version, we don't try to update it.
  837. if (OtherName != NonTargetName) {
  838. // Remove instead of erase, since others may have stored the StringRef
  839. // to this.
  840. const auto ExistingRecord = Manglings.find(NonTargetName);
  841. if (ExistingRecord != std::end(Manglings))
  842. Manglings.remove(&(*ExistingRecord));
  843. auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
  844. MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
  845. if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
  846. Entry->setName(OtherName);
  847. }
  848. }
  849. }
  850. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  851. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  852. // Some ABIs don't have constructor variants. Make sure that base and
  853. // complete constructors get mangled the same.
  854. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  855. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  856. CXXCtorType OrigCtorType = GD.getCtorType();
  857. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  858. if (OrigCtorType == Ctor_Base)
  859. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  860. }
  861. }
  862. auto FoundName = MangledDeclNames.find(CanonicalGD);
  863. if (FoundName != MangledDeclNames.end())
  864. return FoundName->second;
  865. // Keep the first result in the case of a mangling collision.
  866. const auto *ND = cast<NamedDecl>(GD.getDecl());
  867. auto Result =
  868. Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
  869. return MangledDeclNames[CanonicalGD] = Result.first->first();
  870. }
  871. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  872. const BlockDecl *BD) {
  873. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  874. const Decl *D = GD.getDecl();
  875. SmallString<256> Buffer;
  876. llvm::raw_svector_ostream Out(Buffer);
  877. if (!D)
  878. MangleCtx.mangleGlobalBlock(BD,
  879. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  880. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  881. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  882. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  883. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  884. else
  885. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  886. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  887. return Result.first->first();
  888. }
  889. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  890. return getModule().getNamedValue(Name);
  891. }
  892. /// AddGlobalCtor - Add a function to the list that will be called before
  893. /// main() runs.
  894. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  895. llvm::Constant *AssociatedData) {
  896. // FIXME: Type coercion of void()* types.
  897. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  898. }
  899. /// AddGlobalDtor - Add a function to the list that will be called
  900. /// when the module is unloaded.
  901. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  902. // FIXME: Type coercion of void()* types.
  903. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  904. }
  905. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  906. if (Fns.empty()) return;
  907. // Ctor function type is void()*.
  908. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  909. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  910. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  911. llvm::StructType *CtorStructTy = llvm::StructType::get(
  912. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
  913. // Construct the constructor and destructor arrays.
  914. ConstantInitBuilder builder(*this);
  915. auto ctors = builder.beginArray(CtorStructTy);
  916. for (const auto &I : Fns) {
  917. auto ctor = ctors.beginStruct(CtorStructTy);
  918. ctor.addInt(Int32Ty, I.Priority);
  919. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  920. if (I.AssociatedData)
  921. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  922. else
  923. ctor.addNullPointer(VoidPtrTy);
  924. ctor.finishAndAddTo(ctors);
  925. }
  926. auto list =
  927. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  928. /*constant*/ false,
  929. llvm::GlobalValue::AppendingLinkage);
  930. // The LTO linker doesn't seem to like it when we set an alignment
  931. // on appending variables. Take it off as a workaround.
  932. list->setAlignment(0);
  933. Fns.clear();
  934. }
  935. llvm::GlobalValue::LinkageTypes
  936. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  937. const auto *D = cast<FunctionDecl>(GD.getDecl());
  938. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  939. if (isa<CXXDestructorDecl>(D) &&
  940. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  941. GD.getDtorType())) {
  942. // Destructor variants in the Microsoft C++ ABI are always internal or
  943. // linkonce_odr thunks emitted on an as-needed basis.
  944. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  945. : llvm::GlobalValue::LinkOnceODRLinkage;
  946. }
  947. if (isa<CXXConstructorDecl>(D) &&
  948. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  949. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  950. // Our approach to inheriting constructors is fundamentally different from
  951. // that used by the MS ABI, so keep our inheriting constructor thunks
  952. // internal rather than trying to pick an unambiguous mangling for them.
  953. return llvm::GlobalValue::InternalLinkage;
  954. }
  955. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  956. }
  957. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  958. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  959. if (!MDS) return nullptr;
  960. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  961. }
  962. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  963. const CGFunctionInfo &Info,
  964. llvm::Function *F) {
  965. unsigned CallingConv;
  966. llvm::AttributeList PAL;
  967. ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
  968. F->setAttributes(PAL);
  969. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  970. }
  971. /// Determines whether the language options require us to model
  972. /// unwind exceptions. We treat -fexceptions as mandating this
  973. /// except under the fragile ObjC ABI with only ObjC exceptions
  974. /// enabled. This means, for example, that C with -fexceptions
  975. /// enables this.
  976. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  977. // If exceptions are completely disabled, obviously this is false.
  978. if (!LangOpts.Exceptions) return false;
  979. // If C++ exceptions are enabled, this is true.
  980. if (LangOpts.CXXExceptions) return true;
  981. // If ObjC exceptions are enabled, this depends on the ABI.
  982. if (LangOpts.ObjCExceptions) {
  983. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  984. }
  985. return true;
  986. }
  987. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  988. llvm::Function *F) {
  989. llvm::AttrBuilder B;
  990. if (CodeGenOpts.UnwindTables)
  991. B.addAttribute(llvm::Attribute::UWTable);
  992. if (!hasUnwindExceptions(LangOpts))
  993. B.addAttribute(llvm::Attribute::NoUnwind);
  994. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  995. B.addAttribute(llvm::Attribute::StackProtect);
  996. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  997. B.addAttribute(llvm::Attribute::StackProtectStrong);
  998. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  999. B.addAttribute(llvm::Attribute::StackProtectReq);
  1000. if (!D) {
  1001. // If we don't have a declaration to control inlining, the function isn't
  1002. // explicitly marked as alwaysinline for semantic reasons, and inlining is
  1003. // disabled, mark the function as noinline.
  1004. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1005. CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
  1006. B.addAttribute(llvm::Attribute::NoInline);
  1007. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1008. return;
  1009. }
  1010. // Track whether we need to add the optnone LLVM attribute,
  1011. // starting with the default for this optimization level.
  1012. bool ShouldAddOptNone =
  1013. !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
  1014. // We can't add optnone in the following cases, it won't pass the verifier.
  1015. ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
  1016. ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
  1017. ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
  1018. if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
  1019. B.addAttribute(llvm::Attribute::OptimizeNone);
  1020. // OptimizeNone implies noinline; we should not be inlining such functions.
  1021. B.addAttribute(llvm::Attribute::NoInline);
  1022. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1023. "OptimizeNone and AlwaysInline on same function!");
  1024. // We still need to handle naked functions even though optnone subsumes
  1025. // much of their semantics.
  1026. if (D->hasAttr<NakedAttr>())
  1027. B.addAttribute(llvm::Attribute::Naked);
  1028. // OptimizeNone wins over OptimizeForSize and MinSize.
  1029. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  1030. F->removeFnAttr(llvm::Attribute::MinSize);
  1031. } else if (D->hasAttr<NakedAttr>()) {
  1032. // Naked implies noinline: we should not be inlining such functions.
  1033. B.addAttribute(llvm::Attribute::Naked);
  1034. B.addAttribute(llvm::Attribute::NoInline);
  1035. } else if (D->hasAttr<NoDuplicateAttr>()) {
  1036. B.addAttribute(llvm::Attribute::NoDuplicate);
  1037. } else if (D->hasAttr<NoInlineAttr>()) {
  1038. B.addAttribute(llvm::Attribute::NoInline);
  1039. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  1040. !F->hasFnAttribute(llvm::Attribute::NoInline)) {
  1041. // (noinline wins over always_inline, and we can't specify both in IR)
  1042. B.addAttribute(llvm::Attribute::AlwaysInline);
  1043. } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
  1044. // If we're not inlining, then force everything that isn't always_inline to
  1045. // carry an explicit noinline attribute.
  1046. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
  1047. B.addAttribute(llvm::Attribute::NoInline);
  1048. } else {
  1049. // Otherwise, propagate the inline hint attribute and potentially use its
  1050. // absence to mark things as noinline.
  1051. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1052. if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
  1053. return Redecl->isInlineSpecified();
  1054. })) {
  1055. B.addAttribute(llvm::Attribute::InlineHint);
  1056. } else if (CodeGenOpts.getInlining() ==
  1057. CodeGenOptions::OnlyHintInlining &&
  1058. !FD->isInlined() &&
  1059. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  1060. B.addAttribute(llvm::Attribute::NoInline);
  1061. }
  1062. }
  1063. }
  1064. // Add other optimization related attributes if we are optimizing this
  1065. // function.
  1066. if (!D->hasAttr<OptimizeNoneAttr>()) {
  1067. if (D->hasAttr<ColdAttr>()) {
  1068. if (!ShouldAddOptNone)
  1069. B.addAttribute(llvm::Attribute::OptimizeForSize);
  1070. B.addAttribute(llvm::Attribute::Cold);
  1071. }
  1072. if (D->hasAttr<MinSizeAttr>())
  1073. B.addAttribute(llvm::Attribute::MinSize);
  1074. }
  1075. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1076. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  1077. if (alignment)
  1078. F->setAlignment(alignment);
  1079. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  1080. // reserve a bit for differentiating between virtual and non-virtual member
  1081. // functions. If the current target's C++ ABI requires this and this is a
  1082. // member function, set its alignment accordingly.
  1083. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  1084. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  1085. F->setAlignment(2);
  1086. }
  1087. // In the cross-dso CFI mode, we want !type attributes on definitions only.
  1088. if (CodeGenOpts.SanitizeCfiCrossDso)
  1089. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1090. CreateFunctionTypeMetadata(FD, F);
  1091. }
  1092. void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
  1093. const Decl *D = GD.getDecl();
  1094. if (dyn_cast_or_null<NamedDecl>(D))
  1095. setGVProperties(GV, GD);
  1096. else
  1097. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  1098. if (D && D->hasAttr<UsedAttr>())
  1099. addUsedGlobal(GV);
  1100. }
  1101. bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
  1102. llvm::AttrBuilder &Attrs) {
  1103. // Add target-cpu and target-features attributes to functions. If
  1104. // we have a decl for the function and it has a target attribute then
  1105. // parse that and add it to the feature set.
  1106. StringRef TargetCPU = getTarget().getTargetOpts().CPU;
  1107. std::vector<std::string> Features;
  1108. const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
  1109. FD = FD ? FD->getMostRecentDecl() : FD;
  1110. const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
  1111. bool AddedAttr = false;
  1112. if (TD) {
  1113. llvm::StringMap<bool> FeatureMap;
  1114. getFunctionFeatureMap(FeatureMap, FD);
  1115. // Produce the canonical string for this set of features.
  1116. for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
  1117. Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
  1118. // Now add the target-cpu and target-features to the function.
  1119. // While we populated the feature map above, we still need to
  1120. // get and parse the target attribute so we can get the cpu for
  1121. // the function.
  1122. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  1123. if (ParsedAttr.Architecture != "" &&
  1124. getTarget().isValidCPUName(ParsedAttr.Architecture))
  1125. TargetCPU = ParsedAttr.Architecture;
  1126. } else {
  1127. // Otherwise just add the existing target cpu and target features to the
  1128. // function.
  1129. Features = getTarget().getTargetOpts().Features;
  1130. }
  1131. if (TargetCPU != "") {
  1132. Attrs.addAttribute("target-cpu", TargetCPU);
  1133. AddedAttr = true;
  1134. }
  1135. if (!Features.empty()) {
  1136. std::sort(Features.begin(), Features.end());
  1137. Attrs.addAttribute("target-features", llvm::join(Features, ","));
  1138. AddedAttr = true;
  1139. }
  1140. return AddedAttr;
  1141. }
  1142. void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
  1143. llvm::GlobalObject *GO) {
  1144. const Decl *D = GD.getDecl();
  1145. SetCommonAttributes(GD, GO);
  1146. if (D) {
  1147. if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
  1148. if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
  1149. GV->addAttribute("bss-section", SA->getName());
  1150. if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
  1151. GV->addAttribute("data-section", SA->getName());
  1152. if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
  1153. GV->addAttribute("rodata-section", SA->getName());
  1154. }
  1155. if (auto *F = dyn_cast<llvm::Function>(GO)) {
  1156. if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
  1157. if (!D->getAttr<SectionAttr>())
  1158. F->addFnAttr("implicit-section-name", SA->getName());
  1159. llvm::AttrBuilder Attrs;
  1160. if (GetCPUAndFeaturesAttributes(D, Attrs)) {
  1161. // We know that GetCPUAndFeaturesAttributes will always have the
  1162. // newest set, since it has the newest possible FunctionDecl, so the
  1163. // new ones should replace the old.
  1164. F->removeFnAttr("target-cpu");
  1165. F->removeFnAttr("target-features");
  1166. F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
  1167. }
  1168. }
  1169. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  1170. GO->setSection(SA->getName());
  1171. }
  1172. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  1173. }
  1174. void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
  1175. llvm::Function *F,
  1176. const CGFunctionInfo &FI) {
  1177. const Decl *D = GD.getDecl();
  1178. SetLLVMFunctionAttributes(D, FI, F);
  1179. SetLLVMFunctionAttributesForDefinition(D, F);
  1180. F->setLinkage(llvm::Function::InternalLinkage);
  1181. setNonAliasAttributes(GD, F);
  1182. }
  1183. static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
  1184. // Set linkage and visibility in case we never see a definition.
  1185. LinkageInfo LV = ND->getLinkageAndVisibility();
  1186. // Don't set internal linkage on declarations.
  1187. // "extern_weak" is overloaded in LLVM; we probably should have
  1188. // separate linkage types for this.
  1189. if (isExternallyVisible(LV.getLinkage()) &&
  1190. (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
  1191. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1192. }
  1193. void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
  1194. llvm::Function *F) {
  1195. // Only if we are checking indirect calls.
  1196. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  1197. return;
  1198. // Non-static class methods are handled via vtable pointer checks elsewhere.
  1199. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  1200. return;
  1201. // Additionally, if building with cross-DSO support...
  1202. if (CodeGenOpts.SanitizeCfiCrossDso) {
  1203. // Skip available_externally functions. They won't be codegen'ed in the
  1204. // current module anyway.
  1205. if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
  1206. return;
  1207. }
  1208. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  1209. F->addTypeMetadata(0, MD);
  1210. F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
  1211. // Emit a hash-based bit set entry for cross-DSO calls.
  1212. if (CodeGenOpts.SanitizeCfiCrossDso)
  1213. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  1214. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  1215. }
  1216. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  1217. bool IsIncompleteFunction,
  1218. bool IsThunk) {
  1219. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  1220. // If this is an intrinsic function, set the function's attributes
  1221. // to the intrinsic's attributes.
  1222. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  1223. return;
  1224. }
  1225. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1226. if (!IsIncompleteFunction) {
  1227. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  1228. // Setup target-specific attributes.
  1229. if (F->isDeclaration())
  1230. getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
  1231. }
  1232. // Add the Returned attribute for "this", except for iOS 5 and earlier
  1233. // where substantial code, including the libstdc++ dylib, was compiled with
  1234. // GCC and does not actually return "this".
  1235. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  1236. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  1237. assert(!F->arg_empty() &&
  1238. F->arg_begin()->getType()
  1239. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  1240. "unexpected this return");
  1241. F->addAttribute(1, llvm::Attribute::Returned);
  1242. }
  1243. // Only a few attributes are set on declarations; these may later be
  1244. // overridden by a definition.
  1245. setLinkageForGV(F, FD);
  1246. setGVProperties(F, FD);
  1247. if (FD->getAttr<PragmaClangTextSectionAttr>()) {
  1248. F->addFnAttr("implicit-section-name");
  1249. }
  1250. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  1251. F->setSection(SA->getName());
  1252. if (FD->isReplaceableGlobalAllocationFunction()) {
  1253. // A replaceable global allocation function does not act like a builtin by
  1254. // default, only if it is invoked by a new-expression or delete-expression.
  1255. F->addAttribute(llvm::AttributeList::FunctionIndex,
  1256. llvm::Attribute::NoBuiltin);
  1257. // A sane operator new returns a non-aliasing pointer.
  1258. // FIXME: Also add NonNull attribute to the return value
  1259. // for the non-nothrow forms?
  1260. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  1261. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  1262. (Kind == OO_New || Kind == OO_Array_New))
  1263. F->addAttribute(llvm::AttributeList::ReturnIndex,
  1264. llvm::Attribute::NoAlias);
  1265. }
  1266. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  1267. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1268. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  1269. if (MD->isVirtual())
  1270. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1271. // Don't emit entries for function declarations in the cross-DSO mode. This
  1272. // is handled with better precision by the receiving DSO.
  1273. if (!CodeGenOpts.SanitizeCfiCrossDso)
  1274. CreateFunctionTypeMetadata(FD, F);
  1275. if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
  1276. getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
  1277. }
  1278. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  1279. assert(!GV->isDeclaration() &&
  1280. "Only globals with definition can force usage.");
  1281. LLVMUsed.emplace_back(GV);
  1282. }
  1283. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  1284. assert(!GV->isDeclaration() &&
  1285. "Only globals with definition can force usage.");
  1286. LLVMCompilerUsed.emplace_back(GV);
  1287. }
  1288. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  1289. std::vector<llvm::WeakTrackingVH> &List) {
  1290. // Don't create llvm.used if there is no need.
  1291. if (List.empty())
  1292. return;
  1293. // Convert List to what ConstantArray needs.
  1294. SmallVector<llvm::Constant*, 8> UsedArray;
  1295. UsedArray.resize(List.size());
  1296. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  1297. UsedArray[i] =
  1298. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  1299. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  1300. }
  1301. if (UsedArray.empty())
  1302. return;
  1303. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  1304. auto *GV = new llvm::GlobalVariable(
  1305. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  1306. llvm::ConstantArray::get(ATy, UsedArray), Name);
  1307. GV->setSection("llvm.metadata");
  1308. }
  1309. void CodeGenModule::emitLLVMUsed() {
  1310. emitUsed(*this, "llvm.used", LLVMUsed);
  1311. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  1312. }
  1313. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  1314. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  1315. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1316. }
  1317. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  1318. llvm::SmallString<32> Opt;
  1319. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  1320. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1321. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1322. }
  1323. void CodeGenModule::AddELFLibDirective(StringRef Lib) {
  1324. auto &C = getLLVMContext();
  1325. LinkerOptionsMetadata.push_back(llvm::MDNode::get(
  1326. C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
  1327. }
  1328. void CodeGenModule::AddDependentLib(StringRef Lib) {
  1329. llvm::SmallString<24> Opt;
  1330. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1331. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1332. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1333. }
  1334. /// \brief Add link options implied by the given module, including modules
  1335. /// it depends on, using a postorder walk.
  1336. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1337. SmallVectorImpl<llvm::MDNode *> &Metadata,
  1338. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1339. // Import this module's parent.
  1340. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1341. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1342. }
  1343. // Import this module's dependencies.
  1344. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1345. if (Visited.insert(Mod->Imports[I - 1]).second)
  1346. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1347. }
  1348. // Add linker options to link against the libraries/frameworks
  1349. // described by this module.
  1350. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1351. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1352. // Link against a framework. Frameworks are currently Darwin only, so we
  1353. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1354. if (Mod->LinkLibraries[I-1].IsFramework) {
  1355. llvm::Metadata *Args[2] = {
  1356. llvm::MDString::get(Context, "-framework"),
  1357. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1358. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1359. continue;
  1360. }
  1361. // Link against a library.
  1362. llvm::SmallString<24> Opt;
  1363. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1364. Mod->LinkLibraries[I-1].Library, Opt);
  1365. auto *OptString = llvm::MDString::get(Context, Opt);
  1366. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1367. }
  1368. }
  1369. void CodeGenModule::EmitModuleLinkOptions() {
  1370. // Collect the set of all of the modules we want to visit to emit link
  1371. // options, which is essentially the imported modules and all of their
  1372. // non-explicit child modules.
  1373. llvm::SetVector<clang::Module *> LinkModules;
  1374. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1375. SmallVector<clang::Module *, 16> Stack;
  1376. // Seed the stack with imported modules.
  1377. for (Module *M : ImportedModules) {
  1378. // Do not add any link flags when an implementation TU of a module imports
  1379. // a header of that same module.
  1380. if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  1381. !getLangOpts().isCompilingModule())
  1382. continue;
  1383. if (Visited.insert(M).second)
  1384. Stack.push_back(M);
  1385. }
  1386. // Find all of the modules to import, making a little effort to prune
  1387. // non-leaf modules.
  1388. while (!Stack.empty()) {
  1389. clang::Module *Mod = Stack.pop_back_val();
  1390. bool AnyChildren = false;
  1391. // Visit the submodules of this module.
  1392. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  1393. SubEnd = Mod->submodule_end();
  1394. Sub != SubEnd; ++Sub) {
  1395. // Skip explicit children; they need to be explicitly imported to be
  1396. // linked against.
  1397. if ((*Sub)->IsExplicit)
  1398. continue;
  1399. if (Visited.insert(*Sub).second) {
  1400. Stack.push_back(*Sub);
  1401. AnyChildren = true;
  1402. }
  1403. }
  1404. // We didn't find any children, so add this module to the list of
  1405. // modules to link against.
  1406. if (!AnyChildren) {
  1407. LinkModules.insert(Mod);
  1408. }
  1409. }
  1410. // Add link options for all of the imported modules in reverse topological
  1411. // order. We don't do anything to try to order import link flags with respect
  1412. // to linker options inserted by things like #pragma comment().
  1413. SmallVector<llvm::MDNode *, 16> MetadataArgs;
  1414. Visited.clear();
  1415. for (Module *M : LinkModules)
  1416. if (Visited.insert(M).second)
  1417. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1418. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1419. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1420. // Add the linker options metadata flag.
  1421. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
  1422. for (auto *MD : LinkerOptionsMetadata)
  1423. NMD->addOperand(MD);
  1424. }
  1425. void CodeGenModule::EmitDeferred() {
  1426. // Emit code for any potentially referenced deferred decls. Since a
  1427. // previously unused static decl may become used during the generation of code
  1428. // for a static function, iterate until no changes are made.
  1429. if (!DeferredVTables.empty()) {
  1430. EmitDeferredVTables();
  1431. // Emitting a vtable doesn't directly cause more vtables to
  1432. // become deferred, although it can cause functions to be
  1433. // emitted that then need those vtables.
  1434. assert(DeferredVTables.empty());
  1435. }
  1436. // Stop if we're out of both deferred vtables and deferred declarations.
  1437. if (DeferredDeclsToEmit.empty())
  1438. return;
  1439. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1440. // work, it will not interfere with this.
  1441. std::vector<GlobalDecl> CurDeclsToEmit;
  1442. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1443. for (GlobalDecl &D : CurDeclsToEmit) {
  1444. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1445. // to get GlobalValue with exactly the type we need, not something that
  1446. // might had been created for another decl with the same mangled name but
  1447. // different type.
  1448. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1449. GetAddrOfGlobal(D, ForDefinition));
  1450. // In case of different address spaces, we may still get a cast, even with
  1451. // IsForDefinition equal to true. Query mangled names table to get
  1452. // GlobalValue.
  1453. if (!GV)
  1454. GV = GetGlobalValue(getMangledName(D));
  1455. // Make sure GetGlobalValue returned non-null.
  1456. assert(GV);
  1457. // Check to see if we've already emitted this. This is necessary
  1458. // for a couple of reasons: first, decls can end up in the
  1459. // deferred-decls queue multiple times, and second, decls can end
  1460. // up with definitions in unusual ways (e.g. by an extern inline
  1461. // function acquiring a strong function redefinition). Just
  1462. // ignore these cases.
  1463. if (!GV->isDeclaration())
  1464. continue;
  1465. // Otherwise, emit the definition and move on to the next one.
  1466. EmitGlobalDefinition(D, GV);
  1467. // If we found out that we need to emit more decls, do that recursively.
  1468. // This has the advantage that the decls are emitted in a DFS and related
  1469. // ones are close together, which is convenient for testing.
  1470. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1471. EmitDeferred();
  1472. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1473. }
  1474. }
  1475. }
  1476. void CodeGenModule::EmitVTablesOpportunistically() {
  1477. // Try to emit external vtables as available_externally if they have emitted
  1478. // all inlined virtual functions. It runs after EmitDeferred() and therefore
  1479. // is not allowed to create new references to things that need to be emitted
  1480. // lazily. Note that it also uses fact that we eagerly emitting RTTI.
  1481. assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
  1482. && "Only emit opportunistic vtables with optimizations");
  1483. for (const CXXRecordDecl *RD : OpportunisticVTables) {
  1484. assert(getVTables().isVTableExternal(RD) &&
  1485. "This queue should only contain external vtables");
  1486. if (getCXXABI().canSpeculativelyEmitVTable(RD))
  1487. VTables.GenerateClassData(RD);
  1488. }
  1489. OpportunisticVTables.clear();
  1490. }
  1491. void CodeGenModule::EmitGlobalAnnotations() {
  1492. if (Annotations.empty())
  1493. return;
  1494. // Create a new global variable for the ConstantStruct in the Module.
  1495. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1496. Annotations[0]->getType(), Annotations.size()), Annotations);
  1497. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1498. llvm::GlobalValue::AppendingLinkage,
  1499. Array, "llvm.global.annotations");
  1500. gv->setSection(AnnotationSection);
  1501. }
  1502. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1503. llvm::Constant *&AStr = AnnotationStrings[Str];
  1504. if (AStr)
  1505. return AStr;
  1506. // Not found yet, create a new global.
  1507. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1508. auto *gv =
  1509. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1510. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1511. gv->setSection(AnnotationSection);
  1512. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1513. AStr = gv;
  1514. return gv;
  1515. }
  1516. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1517. SourceManager &SM = getContext().getSourceManager();
  1518. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1519. if (PLoc.isValid())
  1520. return EmitAnnotationString(PLoc.getFilename());
  1521. return EmitAnnotationString(SM.getBufferName(Loc));
  1522. }
  1523. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1524. SourceManager &SM = getContext().getSourceManager();
  1525. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1526. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1527. SM.getExpansionLineNumber(L);
  1528. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1529. }
  1530. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1531. const AnnotateAttr *AA,
  1532. SourceLocation L) {
  1533. // Get the globals for file name, annotation, and the line number.
  1534. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1535. *UnitGV = EmitAnnotationUnit(L),
  1536. *LineNoCst = EmitAnnotationLineNo(L);
  1537. // Create the ConstantStruct for the global annotation.
  1538. llvm::Constant *Fields[4] = {
  1539. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1540. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1541. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1542. LineNoCst
  1543. };
  1544. return llvm::ConstantStruct::getAnon(Fields);
  1545. }
  1546. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1547. llvm::GlobalValue *GV) {
  1548. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1549. // Get the struct elements for these annotations.
  1550. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1551. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1552. }
  1553. bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
  1554. llvm::Function *Fn,
  1555. SourceLocation Loc) const {
  1556. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1557. // Blacklist by function name.
  1558. if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
  1559. return true;
  1560. // Blacklist by location.
  1561. if (Loc.isValid())
  1562. return SanitizerBL.isBlacklistedLocation(Kind, Loc);
  1563. // If location is unknown, this may be a compiler-generated function. Assume
  1564. // it's located in the main file.
  1565. auto &SM = Context.getSourceManager();
  1566. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1567. return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
  1568. }
  1569. return false;
  1570. }
  1571. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1572. SourceLocation Loc, QualType Ty,
  1573. StringRef Category) const {
  1574. // For now globals can be blacklisted only in ASan and KASan.
  1575. const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
  1576. (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress);
  1577. if (!EnabledAsanMask)
  1578. return false;
  1579. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1580. if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
  1581. return true;
  1582. if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
  1583. return true;
  1584. // Check global type.
  1585. if (!Ty.isNull()) {
  1586. // Drill down the array types: if global variable of a fixed type is
  1587. // blacklisted, we also don't instrument arrays of them.
  1588. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1589. Ty = AT->getElementType();
  1590. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1591. // We allow to blacklist only record types (classes, structs etc.)
  1592. if (Ty->isRecordType()) {
  1593. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1594. if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
  1595. return true;
  1596. }
  1597. }
  1598. return false;
  1599. }
  1600. bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  1601. StringRef Category) const {
  1602. if (!LangOpts.XRayInstrument)
  1603. return false;
  1604. const auto &XRayFilter = getContext().getXRayFilter();
  1605. using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
  1606. auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
  1607. if (Loc.isValid())
  1608. Attr = XRayFilter.shouldImbueLocation(Loc, Category);
  1609. if (Attr == ImbueAttr::NONE)
  1610. Attr = XRayFilter.shouldImbueFunction(Fn->getName());
  1611. switch (Attr) {
  1612. case ImbueAttr::NONE:
  1613. return false;
  1614. case ImbueAttr::ALWAYS:
  1615. Fn->addFnAttr("function-instrument", "xray-always");
  1616. break;
  1617. case ImbueAttr::ALWAYS_ARG1:
  1618. Fn->addFnAttr("function-instrument", "xray-always");
  1619. Fn->addFnAttr("xray-log-args", "1");
  1620. break;
  1621. case ImbueAttr::NEVER:
  1622. Fn->addFnAttr("function-instrument", "xray-never");
  1623. break;
  1624. }
  1625. return true;
  1626. }
  1627. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1628. // Never defer when EmitAllDecls is specified.
  1629. if (LangOpts.EmitAllDecls)
  1630. return true;
  1631. return getContext().DeclMustBeEmitted(Global);
  1632. }
  1633. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1634. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1635. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1636. // Implicit template instantiations may change linkage if they are later
  1637. // explicitly instantiated, so they should not be emitted eagerly.
  1638. return false;
  1639. if (const auto *VD = dyn_cast<VarDecl>(Global))
  1640. if (Context.getInlineVariableDefinitionKind(VD) ==
  1641. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  1642. // A definition of an inline constexpr static data member may change
  1643. // linkage later if it's redeclared outside the class.
  1644. return false;
  1645. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1646. // codegen for global variables, because they may be marked as threadprivate.
  1647. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1648. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
  1649. return false;
  1650. return true;
  1651. }
  1652. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  1653. const CXXUuidofExpr* E) {
  1654. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1655. // well-formed.
  1656. StringRef Uuid = E->getUuidStr();
  1657. std::string Name = "_GUID_" + Uuid.lower();
  1658. std::replace(Name.begin(), Name.end(), '-', '_');
  1659. // The UUID descriptor should be pointer aligned.
  1660. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  1661. // Look for an existing global.
  1662. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1663. return ConstantAddress(GV, Alignment);
  1664. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1665. assert(Init && "failed to initialize as constant");
  1666. auto *GV = new llvm::GlobalVariable(
  1667. getModule(), Init->getType(),
  1668. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1669. if (supportsCOMDAT())
  1670. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1671. return ConstantAddress(GV, Alignment);
  1672. }
  1673. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1674. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1675. assert(AA && "No alias?");
  1676. CharUnits Alignment = getContext().getDeclAlign(VD);
  1677. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1678. // See if there is already something with the target's name in the module.
  1679. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1680. if (Entry) {
  1681. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1682. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1683. return ConstantAddress(Ptr, Alignment);
  1684. }
  1685. llvm::Constant *Aliasee;
  1686. if (isa<llvm::FunctionType>(DeclTy))
  1687. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1688. GlobalDecl(cast<FunctionDecl>(VD)),
  1689. /*ForVTable=*/false);
  1690. else
  1691. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1692. llvm::PointerType::getUnqual(DeclTy),
  1693. nullptr);
  1694. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1695. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1696. WeakRefReferences.insert(F);
  1697. return ConstantAddress(Aliasee, Alignment);
  1698. }
  1699. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1700. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1701. // Weak references don't produce any output by themselves.
  1702. if (Global->hasAttr<WeakRefAttr>())
  1703. return;
  1704. // If this is an alias definition (which otherwise looks like a declaration)
  1705. // emit it now.
  1706. if (Global->hasAttr<AliasAttr>())
  1707. return EmitAliasDefinition(GD);
  1708. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  1709. if (Global->hasAttr<IFuncAttr>())
  1710. return emitIFuncDefinition(GD);
  1711. // If this is CUDA, be selective about which declarations we emit.
  1712. if (LangOpts.CUDA) {
  1713. if (LangOpts.CUDAIsDevice) {
  1714. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1715. !Global->hasAttr<CUDAGlobalAttr>() &&
  1716. !Global->hasAttr<CUDAConstantAttr>() &&
  1717. !Global->hasAttr<CUDASharedAttr>())
  1718. return;
  1719. } else {
  1720. // We need to emit host-side 'shadows' for all global
  1721. // device-side variables because the CUDA runtime needs their
  1722. // size and host-side address in order to provide access to
  1723. // their device-side incarnations.
  1724. // So device-only functions are the only things we skip.
  1725. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  1726. Global->hasAttr<CUDADeviceAttr>())
  1727. return;
  1728. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  1729. "Expected Variable or Function");
  1730. }
  1731. }
  1732. if (LangOpts.OpenMP) {
  1733. // If this is OpenMP device, check if it is legal to emit this global
  1734. // normally.
  1735. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  1736. return;
  1737. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  1738. if (MustBeEmitted(Global))
  1739. EmitOMPDeclareReduction(DRD);
  1740. return;
  1741. }
  1742. }
  1743. // Ignore declarations, they will be emitted on their first use.
  1744. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1745. // Forward declarations are emitted lazily on first use.
  1746. if (!FD->doesThisDeclarationHaveABody()) {
  1747. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1748. return;
  1749. StringRef MangledName = getMangledName(GD);
  1750. // Compute the function info and LLVM type.
  1751. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1752. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1753. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1754. /*DontDefer=*/false);
  1755. return;
  1756. }
  1757. } else {
  1758. const auto *VD = cast<VarDecl>(Global);
  1759. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1760. // We need to emit device-side global CUDA variables even if a
  1761. // variable does not have a definition -- we still need to define
  1762. // host-side shadow for it.
  1763. bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  1764. !VD->hasDefinition() &&
  1765. (VD->hasAttr<CUDAConstantAttr>() ||
  1766. VD->hasAttr<CUDADeviceAttr>());
  1767. if (!MustEmitForCuda &&
  1768. VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1769. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  1770. // If this declaration may have caused an inline variable definition to
  1771. // change linkage, make sure that it's emitted.
  1772. if (Context.getInlineVariableDefinitionKind(VD) ==
  1773. ASTContext::InlineVariableDefinitionKind::Strong)
  1774. GetAddrOfGlobalVar(VD);
  1775. return;
  1776. }
  1777. }
  1778. // Defer code generation to first use when possible, e.g. if this is an inline
  1779. // function. If the global must always be emitted, do it eagerly if possible
  1780. // to benefit from cache locality.
  1781. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1782. // Emit the definition if it can't be deferred.
  1783. EmitGlobalDefinition(GD);
  1784. return;
  1785. }
  1786. // If we're deferring emission of a C++ variable with an
  1787. // initializer, remember the order in which it appeared in the file.
  1788. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1789. cast<VarDecl>(Global)->hasInit()) {
  1790. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1791. CXXGlobalInits.push_back(nullptr);
  1792. }
  1793. StringRef MangledName = getMangledName(GD);
  1794. if (GetGlobalValue(MangledName) != nullptr) {
  1795. // The value has already been used and should therefore be emitted.
  1796. addDeferredDeclToEmit(GD);
  1797. } else if (MustBeEmitted(Global)) {
  1798. // The value must be emitted, but cannot be emitted eagerly.
  1799. assert(!MayBeEmittedEagerly(Global));
  1800. addDeferredDeclToEmit(GD);
  1801. } else {
  1802. // Otherwise, remember that we saw a deferred decl with this name. The
  1803. // first use of the mangled name will cause it to move into
  1804. // DeferredDeclsToEmit.
  1805. DeferredDecls[MangledName] = GD;
  1806. }
  1807. }
  1808. // Check if T is a class type with a destructor that's not dllimport.
  1809. static bool HasNonDllImportDtor(QualType T) {
  1810. if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
  1811. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1812. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  1813. return true;
  1814. return false;
  1815. }
  1816. namespace {
  1817. struct FunctionIsDirectlyRecursive :
  1818. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1819. const StringRef Name;
  1820. const Builtin::Context &BI;
  1821. bool Result;
  1822. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1823. Name(N), BI(C), Result(false) {
  1824. }
  1825. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1826. bool TraverseCallExpr(CallExpr *E) {
  1827. const FunctionDecl *FD = E->getDirectCallee();
  1828. if (!FD)
  1829. return true;
  1830. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1831. if (Attr && Name == Attr->getLabel()) {
  1832. Result = true;
  1833. return false;
  1834. }
  1835. unsigned BuiltinID = FD->getBuiltinID();
  1836. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  1837. return true;
  1838. StringRef BuiltinName = BI.getName(BuiltinID);
  1839. if (BuiltinName.startswith("__builtin_") &&
  1840. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1841. Result = true;
  1842. return false;
  1843. }
  1844. return true;
  1845. }
  1846. };
  1847. // Make sure we're not referencing non-imported vars or functions.
  1848. struct DLLImportFunctionVisitor
  1849. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  1850. bool SafeToInline = true;
  1851. bool shouldVisitImplicitCode() const { return true; }
  1852. bool VisitVarDecl(VarDecl *VD) {
  1853. if (VD->getTLSKind()) {
  1854. // A thread-local variable cannot be imported.
  1855. SafeToInline = false;
  1856. return SafeToInline;
  1857. }
  1858. // A variable definition might imply a destructor call.
  1859. if (VD->isThisDeclarationADefinition())
  1860. SafeToInline = !HasNonDllImportDtor(VD->getType());
  1861. return SafeToInline;
  1862. }
  1863. bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  1864. if (const auto *D = E->getTemporary()->getDestructor())
  1865. SafeToInline = D->hasAttr<DLLImportAttr>();
  1866. return SafeToInline;
  1867. }
  1868. bool VisitDeclRefExpr(DeclRefExpr *E) {
  1869. ValueDecl *VD = E->getDecl();
  1870. if (isa<FunctionDecl>(VD))
  1871. SafeToInline = VD->hasAttr<DLLImportAttr>();
  1872. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  1873. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  1874. return SafeToInline;
  1875. }
  1876. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  1877. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  1878. return SafeToInline;
  1879. }
  1880. bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  1881. CXXMethodDecl *M = E->getMethodDecl();
  1882. if (!M) {
  1883. // Call through a pointer to member function. This is safe to inline.
  1884. SafeToInline = true;
  1885. } else {
  1886. SafeToInline = M->hasAttr<DLLImportAttr>();
  1887. }
  1888. return SafeToInline;
  1889. }
  1890. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  1891. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  1892. return SafeToInline;
  1893. }
  1894. bool VisitCXXNewExpr(CXXNewExpr *E) {
  1895. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  1896. return SafeToInline;
  1897. }
  1898. };
  1899. }
  1900. // isTriviallyRecursive - Check if this function calls another
  1901. // decl that, because of the asm attribute or the other decl being a builtin,
  1902. // ends up pointing to itself.
  1903. bool
  1904. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1905. StringRef Name;
  1906. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1907. // asm labels are a special kind of mangling we have to support.
  1908. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1909. if (!Attr)
  1910. return false;
  1911. Name = Attr->getLabel();
  1912. } else {
  1913. Name = FD->getName();
  1914. }
  1915. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1916. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1917. return Walker.Result;
  1918. }
  1919. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1920. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1921. return true;
  1922. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1923. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1924. return false;
  1925. if (F->hasAttr<DLLImportAttr>()) {
  1926. // Check whether it would be safe to inline this dllimport function.
  1927. DLLImportFunctionVisitor Visitor;
  1928. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  1929. if (!Visitor.SafeToInline)
  1930. return false;
  1931. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  1932. // Implicit destructor invocations aren't captured in the AST, so the
  1933. // check above can't see them. Check for them manually here.
  1934. for (const Decl *Member : Dtor->getParent()->decls())
  1935. if (isa<FieldDecl>(Member))
  1936. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  1937. return false;
  1938. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  1939. if (HasNonDllImportDtor(B.getType()))
  1940. return false;
  1941. }
  1942. }
  1943. // PR9614. Avoid cases where the source code is lying to us. An available
  1944. // externally function should have an equivalent function somewhere else,
  1945. // but a function that calls itself is clearly not equivalent to the real
  1946. // implementation.
  1947. // This happens in glibc's btowc and in some configure checks.
  1948. return !isTriviallyRecursive(F);
  1949. }
  1950. bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
  1951. return CodeGenOpts.OptimizationLevel > 0;
  1952. }
  1953. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1954. const auto *D = cast<ValueDecl>(GD.getDecl());
  1955. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1956. Context.getSourceManager(),
  1957. "Generating code for declaration");
  1958. if (isa<FunctionDecl>(D)) {
  1959. // At -O0, don't generate IR for functions with available_externally
  1960. // linkage.
  1961. if (!shouldEmitFunction(GD))
  1962. return;
  1963. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1964. // Make sure to emit the definition(s) before we emit the thunks.
  1965. // This is necessary for the generation of certain thunks.
  1966. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1967. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1968. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1969. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1970. else
  1971. EmitGlobalFunctionDefinition(GD, GV);
  1972. if (Method->isVirtual())
  1973. getVTables().EmitThunks(GD);
  1974. return;
  1975. }
  1976. return EmitGlobalFunctionDefinition(GD, GV);
  1977. }
  1978. if (const auto *VD = dyn_cast<VarDecl>(D))
  1979. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  1980. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1981. }
  1982. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1983. llvm::Function *NewFn);
  1984. void CodeGenModule::emitMultiVersionFunctions() {
  1985. for (GlobalDecl GD : MultiVersionFuncs) {
  1986. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  1987. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1988. getContext().forEachMultiversionedFunctionVersion(
  1989. FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
  1990. GlobalDecl CurGD{
  1991. (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
  1992. StringRef MangledName = getMangledName(CurGD);
  1993. llvm::Constant *Func = GetGlobalValue(MangledName);
  1994. if (!Func) {
  1995. if (CurFD->isDefined()) {
  1996. EmitGlobalFunctionDefinition(CurGD, nullptr);
  1997. Func = GetGlobalValue(MangledName);
  1998. } else {
  1999. const CGFunctionInfo &FI =
  2000. getTypes().arrangeGlobalDeclaration(GD);
  2001. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2002. Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
  2003. /*DontDefer=*/false, ForDefinition);
  2004. }
  2005. assert(Func && "This should have just been created");
  2006. }
  2007. Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
  2008. CurFD->getAttr<TargetAttr>()->parse());
  2009. });
  2010. llvm::Function *ResolverFunc = cast<llvm::Function>(
  2011. GetGlobalValue((getMangledName(GD) + ".resolver").str()));
  2012. if (supportsCOMDAT())
  2013. ResolverFunc->setComdat(
  2014. getModule().getOrInsertComdat(ResolverFunc->getName()));
  2015. std::stable_sort(
  2016. Options.begin(), Options.end(),
  2017. std::greater<CodeGenFunction::MultiVersionResolverOption>());
  2018. CodeGenFunction CGF(*this);
  2019. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  2020. }
  2021. }
  2022. /// If an ifunc for the specified mangled name is not in the module, create and
  2023. /// return an llvm IFunc Function with the specified type.
  2024. llvm::Constant *
  2025. CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
  2026. StringRef MangledName,
  2027. const FunctionDecl *FD) {
  2028. std::string IFuncName = (MangledName + ".ifunc").str();
  2029. if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
  2030. return IFuncGV;
  2031. // Since this is the first time we've created this IFunc, make sure
  2032. // that we put this multiversioned function into the list to be
  2033. // replaced later.
  2034. MultiVersionFuncs.push_back(GD);
  2035. std::string ResolverName = (MangledName + ".resolver").str();
  2036. llvm::Type *ResolverType = llvm::FunctionType::get(
  2037. llvm::PointerType::get(DeclTy,
  2038. Context.getTargetAddressSpace(FD->getType())),
  2039. false);
  2040. llvm::Constant *Resolver =
  2041. GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
  2042. /*ForVTable=*/false);
  2043. llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
  2044. DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
  2045. GIF->setName(IFuncName);
  2046. SetCommonAttributes(FD, GIF);
  2047. return GIF;
  2048. }
  2049. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  2050. /// module, create and return an llvm Function with the specified type. If there
  2051. /// is something in the module with the specified name, return it potentially
  2052. /// bitcasted to the right type.
  2053. ///
  2054. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2055. /// to set the attributes on the function when it is first created.
  2056. llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
  2057. StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
  2058. bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
  2059. ForDefinition_t IsForDefinition) {
  2060. const Decl *D = GD.getDecl();
  2061. // Any attempts to use a MultiVersion function should result in retrieving
  2062. // the iFunc instead. Name Mangling will handle the rest of the changes.
  2063. if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
  2064. if (FD->isMultiVersion() && FD->getAttr<TargetAttr>()->isDefaultVersion()) {
  2065. UpdateMultiVersionNames(GD, FD);
  2066. if (!IsForDefinition)
  2067. return GetOrCreateMultiVersionIFunc(GD, Ty, MangledName, FD);
  2068. }
  2069. }
  2070. // Lookup the entry, lazily creating it if necessary.
  2071. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2072. if (Entry) {
  2073. if (WeakRefReferences.erase(Entry)) {
  2074. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  2075. if (FD && !FD->hasAttr<WeakAttr>())
  2076. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2077. }
  2078. // Handle dropped DLL attributes.
  2079. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2080. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2081. // If there are two attempts to define the same mangled name, issue an
  2082. // error.
  2083. if (IsForDefinition && !Entry->isDeclaration()) {
  2084. GlobalDecl OtherGD;
  2085. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  2086. // to make sure that we issue an error only once.
  2087. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2088. (GD.getCanonicalDecl().getDecl() !=
  2089. OtherGD.getCanonicalDecl().getDecl()) &&
  2090. DiagnosedConflictingDefinitions.insert(GD).second) {
  2091. getDiags().Report(D->getLocation(),
  2092. diag::err_duplicate_mangled_name);
  2093. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2094. diag::note_previous_definition);
  2095. }
  2096. }
  2097. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  2098. (Entry->getType()->getElementType() == Ty)) {
  2099. return Entry;
  2100. }
  2101. // Make sure the result is of the correct type.
  2102. // (If function is requested for a definition, we always need to create a new
  2103. // function, not just return a bitcast.)
  2104. if (!IsForDefinition)
  2105. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  2106. }
  2107. // This function doesn't have a complete type (for example, the return
  2108. // type is an incomplete struct). Use a fake type instead, and make
  2109. // sure not to try to set attributes.
  2110. bool IsIncompleteFunction = false;
  2111. llvm::FunctionType *FTy;
  2112. if (isa<llvm::FunctionType>(Ty)) {
  2113. FTy = cast<llvm::FunctionType>(Ty);
  2114. } else {
  2115. FTy = llvm::FunctionType::get(VoidTy, false);
  2116. IsIncompleteFunction = true;
  2117. }
  2118. llvm::Function *F =
  2119. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  2120. Entry ? StringRef() : MangledName, &getModule());
  2121. // If we already created a function with the same mangled name (but different
  2122. // type) before, take its name and add it to the list of functions to be
  2123. // replaced with F at the end of CodeGen.
  2124. //
  2125. // This happens if there is a prototype for a function (e.g. "int f()") and
  2126. // then a definition of a different type (e.g. "int f(int x)").
  2127. if (Entry) {
  2128. F->takeName(Entry);
  2129. // This might be an implementation of a function without a prototype, in
  2130. // which case, try to do special replacement of calls which match the new
  2131. // prototype. The really key thing here is that we also potentially drop
  2132. // arguments from the call site so as to make a direct call, which makes the
  2133. // inliner happier and suppresses a number of optimizer warnings (!) about
  2134. // dropping arguments.
  2135. if (!Entry->use_empty()) {
  2136. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  2137. Entry->removeDeadConstantUsers();
  2138. }
  2139. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  2140. F, Entry->getType()->getElementType()->getPointerTo());
  2141. addGlobalValReplacement(Entry, BC);
  2142. }
  2143. assert(F->getName() == MangledName && "name was uniqued!");
  2144. if (D)
  2145. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  2146. if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
  2147. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
  2148. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  2149. }
  2150. if (!DontDefer) {
  2151. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  2152. // each other bottoming out with the base dtor. Therefore we emit non-base
  2153. // dtors on usage, even if there is no dtor definition in the TU.
  2154. if (D && isa<CXXDestructorDecl>(D) &&
  2155. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  2156. GD.getDtorType()))
  2157. addDeferredDeclToEmit(GD);
  2158. // This is the first use or definition of a mangled name. If there is a
  2159. // deferred decl with this name, remember that we need to emit it at the end
  2160. // of the file.
  2161. auto DDI = DeferredDecls.find(MangledName);
  2162. if (DDI != DeferredDecls.end()) {
  2163. // Move the potentially referenced deferred decl to the
  2164. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  2165. // don't need it anymore).
  2166. addDeferredDeclToEmit(DDI->second);
  2167. DeferredDecls.erase(DDI);
  2168. // Otherwise, there are cases we have to worry about where we're
  2169. // using a declaration for which we must emit a definition but where
  2170. // we might not find a top-level definition:
  2171. // - member functions defined inline in their classes
  2172. // - friend functions defined inline in some class
  2173. // - special member functions with implicit definitions
  2174. // If we ever change our AST traversal to walk into class methods,
  2175. // this will be unnecessary.
  2176. //
  2177. // We also don't emit a definition for a function if it's going to be an
  2178. // entry in a vtable, unless it's already marked as used.
  2179. } else if (getLangOpts().CPlusPlus && D) {
  2180. // Look for a declaration that's lexically in a record.
  2181. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  2182. FD = FD->getPreviousDecl()) {
  2183. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  2184. if (FD->doesThisDeclarationHaveABody()) {
  2185. addDeferredDeclToEmit(GD.getWithDecl(FD));
  2186. break;
  2187. }
  2188. }
  2189. }
  2190. }
  2191. }
  2192. // Make sure the result is of the requested type.
  2193. if (!IsIncompleteFunction) {
  2194. assert(F->getType()->getElementType() == Ty);
  2195. return F;
  2196. }
  2197. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2198. return llvm::ConstantExpr::getBitCast(F, PTy);
  2199. }
  2200. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  2201. /// non-null, then this function will use the specified type if it has to
  2202. /// create it (this occurs when we see a definition of the function).
  2203. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  2204. llvm::Type *Ty,
  2205. bool ForVTable,
  2206. bool DontDefer,
  2207. ForDefinition_t IsForDefinition) {
  2208. // If there was no specific requested type, just convert it now.
  2209. if (!Ty) {
  2210. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2211. auto CanonTy = Context.getCanonicalType(FD->getType());
  2212. Ty = getTypes().ConvertFunctionType(CanonTy, FD);
  2213. }
  2214. StringRef MangledName = getMangledName(GD);
  2215. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  2216. /*IsThunk=*/false, llvm::AttributeList(),
  2217. IsForDefinition);
  2218. }
  2219. static const FunctionDecl *
  2220. GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
  2221. TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
  2222. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2223. IdentifierInfo &CII = C.Idents.get(Name);
  2224. for (const auto &Result : DC->lookup(&CII))
  2225. if (const auto FD = dyn_cast<FunctionDecl>(Result))
  2226. return FD;
  2227. if (!C.getLangOpts().CPlusPlus)
  2228. return nullptr;
  2229. // Demangle the premangled name from getTerminateFn()
  2230. IdentifierInfo &CXXII =
  2231. (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
  2232. ? C.Idents.get("terminate")
  2233. : C.Idents.get(Name);
  2234. for (const auto &N : {"__cxxabiv1", "std"}) {
  2235. IdentifierInfo &NS = C.Idents.get(N);
  2236. for (const auto &Result : DC->lookup(&NS)) {
  2237. NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
  2238. if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
  2239. for (const auto &Result : LSD->lookup(&NS))
  2240. if ((ND = dyn_cast<NamespaceDecl>(Result)))
  2241. break;
  2242. if (ND)
  2243. for (const auto &Result : ND->lookup(&CXXII))
  2244. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  2245. return FD;
  2246. }
  2247. }
  2248. return nullptr;
  2249. }
  2250. /// CreateRuntimeFunction - Create a new runtime function with the specified
  2251. /// type and name.
  2252. llvm::Constant *
  2253. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
  2254. llvm::AttributeList ExtraAttrs,
  2255. bool Local) {
  2256. llvm::Constant *C =
  2257. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  2258. /*DontDefer=*/false, /*IsThunk=*/false,
  2259. ExtraAttrs);
  2260. if (auto *F = dyn_cast<llvm::Function>(C)) {
  2261. if (F->empty()) {
  2262. F->setCallingConv(getRuntimeCC());
  2263. if (!Local && getTriple().isOSBinFormatCOFF() &&
  2264. !getCodeGenOpts().LTOVisibilityPublicStd &&
  2265. !getTriple().isWindowsGNUEnvironment()) {
  2266. const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
  2267. if (!FD || FD->hasAttr<DLLImportAttr>()) {
  2268. F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2269. F->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2270. }
  2271. }
  2272. }
  2273. }
  2274. return C;
  2275. }
  2276. /// CreateBuiltinFunction - Create a new builtin function with the specified
  2277. /// type and name.
  2278. llvm::Constant *
  2279. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
  2280. llvm::AttributeList ExtraAttrs) {
  2281. llvm::Constant *C =
  2282. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  2283. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  2284. if (auto *F = dyn_cast<llvm::Function>(C))
  2285. if (F->empty())
  2286. F->setCallingConv(getBuiltinCC());
  2287. return C;
  2288. }
  2289. /// isTypeConstant - Determine whether an object of this type can be emitted
  2290. /// as a constant.
  2291. ///
  2292. /// If ExcludeCtor is true, the duration when the object's constructor runs
  2293. /// will not be considered. The caller will need to verify that the object is
  2294. /// not written to during its construction.
  2295. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  2296. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  2297. return false;
  2298. if (Context.getLangOpts().CPlusPlus) {
  2299. if (const CXXRecordDecl *Record
  2300. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  2301. return ExcludeCtor && !Record->hasMutableFields() &&
  2302. Record->hasTrivialDestructor();
  2303. }
  2304. return true;
  2305. }
  2306. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  2307. /// create and return an llvm GlobalVariable with the specified type. If there
  2308. /// is something in the module with the specified name, return it potentially
  2309. /// bitcasted to the right type.
  2310. ///
  2311. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2312. /// to set the attributes on the global when it is first created.
  2313. ///
  2314. /// If IsForDefinition is true, it is guranteed that an actual global with
  2315. /// type Ty will be returned, not conversion of a variable with the same
  2316. /// mangled name but some other type.
  2317. llvm::Constant *
  2318. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  2319. llvm::PointerType *Ty,
  2320. const VarDecl *D,
  2321. ForDefinition_t IsForDefinition) {
  2322. // Lookup the entry, lazily creating it if necessary.
  2323. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2324. if (Entry) {
  2325. if (WeakRefReferences.erase(Entry)) {
  2326. if (D && !D->hasAttr<WeakAttr>())
  2327. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2328. }
  2329. // Handle dropped DLL attributes.
  2330. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2331. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2332. if (Entry->getType() == Ty)
  2333. return Entry;
  2334. // If there are two attempts to define the same mangled name, issue an
  2335. // error.
  2336. if (IsForDefinition && !Entry->isDeclaration()) {
  2337. GlobalDecl OtherGD;
  2338. const VarDecl *OtherD;
  2339. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  2340. // to make sure that we issue an error only once.
  2341. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  2342. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  2343. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  2344. OtherD->hasInit() &&
  2345. DiagnosedConflictingDefinitions.insert(D).second) {
  2346. getDiags().Report(D->getLocation(),
  2347. diag::err_duplicate_mangled_name);
  2348. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2349. diag::note_previous_definition);
  2350. }
  2351. }
  2352. // Make sure the result is of the correct type.
  2353. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  2354. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  2355. // (If global is requested for a definition, we always need to create a new
  2356. // global, not just return a bitcast.)
  2357. if (!IsForDefinition)
  2358. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  2359. }
  2360. auto AddrSpace = GetGlobalVarAddressSpace(D);
  2361. auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
  2362. auto *GV = new llvm::GlobalVariable(
  2363. getModule(), Ty->getElementType(), false,
  2364. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  2365. llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
  2366. // If we already created a global with the same mangled name (but different
  2367. // type) before, take its name and remove it from its parent.
  2368. if (Entry) {
  2369. GV->takeName(Entry);
  2370. if (!Entry->use_empty()) {
  2371. llvm::Constant *NewPtrForOldDecl =
  2372. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2373. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2374. }
  2375. Entry->eraseFromParent();
  2376. }
  2377. // This is the first use or definition of a mangled name. If there is a
  2378. // deferred decl with this name, remember that we need to emit it at the end
  2379. // of the file.
  2380. auto DDI = DeferredDecls.find(MangledName);
  2381. if (DDI != DeferredDecls.end()) {
  2382. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  2383. // list, and remove it from DeferredDecls (since we don't need it anymore).
  2384. addDeferredDeclToEmit(DDI->second);
  2385. DeferredDecls.erase(DDI);
  2386. }
  2387. // Handle things which are present even on external declarations.
  2388. if (D) {
  2389. // FIXME: This code is overly simple and should be merged with other global
  2390. // handling.
  2391. GV->setConstant(isTypeConstant(D->getType(), false));
  2392. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2393. setLinkageForGV(GV, D);
  2394. if (D->getTLSKind()) {
  2395. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2396. CXXThreadLocals.push_back(D);
  2397. setTLSMode(GV, *D);
  2398. }
  2399. setGVProperties(GV, D);
  2400. // If required by the ABI, treat declarations of static data members with
  2401. // inline initializers as definitions.
  2402. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  2403. EmitGlobalVarDefinition(D);
  2404. }
  2405. // Emit section information for extern variables.
  2406. if (D->hasExternalStorage()) {
  2407. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  2408. GV->setSection(SA->getName());
  2409. }
  2410. // Handle XCore specific ABI requirements.
  2411. if (getTriple().getArch() == llvm::Triple::xcore &&
  2412. D->getLanguageLinkage() == CLanguageLinkage &&
  2413. D->getType().isConstant(Context) &&
  2414. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  2415. GV->setSection(".cp.rodata");
  2416. // Check if we a have a const declaration with an initializer, we may be
  2417. // able to emit it as available_externally to expose it's value to the
  2418. // optimizer.
  2419. if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
  2420. D->getType().isConstQualified() && !GV->hasInitializer() &&
  2421. !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
  2422. const auto *Record =
  2423. Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
  2424. bool HasMutableFields = Record && Record->hasMutableFields();
  2425. if (!HasMutableFields) {
  2426. const VarDecl *InitDecl;
  2427. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2428. if (InitExpr) {
  2429. ConstantEmitter emitter(*this);
  2430. llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
  2431. if (Init) {
  2432. auto *InitType = Init->getType();
  2433. if (GV->getType()->getElementType() != InitType) {
  2434. // The type of the initializer does not match the definition.
  2435. // This happens when an initializer has a different type from
  2436. // the type of the global (because of padding at the end of a
  2437. // structure for instance).
  2438. GV->setName(StringRef());
  2439. // Make a new global with the correct type, this is now guaranteed
  2440. // to work.
  2441. auto *NewGV = cast<llvm::GlobalVariable>(
  2442. GetAddrOfGlobalVar(D, InitType, IsForDefinition));
  2443. // Erase the old global, since it is no longer used.
  2444. GV->eraseFromParent();
  2445. GV = NewGV;
  2446. } else {
  2447. GV->setInitializer(Init);
  2448. GV->setConstant(true);
  2449. GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  2450. }
  2451. emitter.finalize(GV);
  2452. }
  2453. }
  2454. }
  2455. }
  2456. }
  2457. LangAS ExpectedAS =
  2458. D ? D->getType().getAddressSpace()
  2459. : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
  2460. assert(getContext().getTargetAddressSpace(ExpectedAS) ==
  2461. Ty->getPointerAddressSpace());
  2462. if (AddrSpace != ExpectedAS)
  2463. return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
  2464. ExpectedAS, Ty);
  2465. return GV;
  2466. }
  2467. llvm::Constant *
  2468. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  2469. ForDefinition_t IsForDefinition) {
  2470. const Decl *D = GD.getDecl();
  2471. if (isa<CXXConstructorDecl>(D))
  2472. return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
  2473. getFromCtorType(GD.getCtorType()),
  2474. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2475. /*DontDefer=*/false, IsForDefinition);
  2476. else if (isa<CXXDestructorDecl>(D))
  2477. return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
  2478. getFromDtorType(GD.getDtorType()),
  2479. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2480. /*DontDefer=*/false, IsForDefinition);
  2481. else if (isa<CXXMethodDecl>(D)) {
  2482. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  2483. cast<CXXMethodDecl>(D));
  2484. auto Ty = getTypes().GetFunctionType(*FInfo);
  2485. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2486. IsForDefinition);
  2487. } else if (isa<FunctionDecl>(D)) {
  2488. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2489. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2490. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2491. IsForDefinition);
  2492. } else
  2493. return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
  2494. IsForDefinition);
  2495. }
  2496. llvm::GlobalVariable *
  2497. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  2498. llvm::Type *Ty,
  2499. llvm::GlobalValue::LinkageTypes Linkage) {
  2500. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  2501. llvm::GlobalVariable *OldGV = nullptr;
  2502. if (GV) {
  2503. // Check if the variable has the right type.
  2504. if (GV->getType()->getElementType() == Ty)
  2505. return GV;
  2506. // Because C++ name mangling, the only way we can end up with an already
  2507. // existing global with the same name is if it has been declared extern "C".
  2508. assert(GV->isDeclaration() && "Declaration has wrong type!");
  2509. OldGV = GV;
  2510. }
  2511. // Create a new variable.
  2512. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  2513. Linkage, nullptr, Name);
  2514. if (OldGV) {
  2515. // Replace occurrences of the old variable if needed.
  2516. GV->takeName(OldGV);
  2517. if (!OldGV->use_empty()) {
  2518. llvm::Constant *NewPtrForOldDecl =
  2519. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2520. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  2521. }
  2522. OldGV->eraseFromParent();
  2523. }
  2524. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  2525. !GV->hasAvailableExternallyLinkage())
  2526. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2527. return GV;
  2528. }
  2529. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  2530. /// given global variable. If Ty is non-null and if the global doesn't exist,
  2531. /// then it will be created with the specified type instead of whatever the
  2532. /// normal requested type would be. If IsForDefinition is true, it is guranteed
  2533. /// that an actual global with type Ty will be returned, not conversion of a
  2534. /// variable with the same mangled name but some other type.
  2535. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  2536. llvm::Type *Ty,
  2537. ForDefinition_t IsForDefinition) {
  2538. assert(D->hasGlobalStorage() && "Not a global variable");
  2539. QualType ASTTy = D->getType();
  2540. if (!Ty)
  2541. Ty = getTypes().ConvertTypeForMem(ASTTy);
  2542. llvm::PointerType *PTy =
  2543. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  2544. StringRef MangledName = getMangledName(D);
  2545. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  2546. }
  2547. /// CreateRuntimeVariable - Create a new runtime global variable with the
  2548. /// specified type and name.
  2549. llvm::Constant *
  2550. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  2551. StringRef Name) {
  2552. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  2553. }
  2554. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  2555. assert(!D->getInit() && "Cannot emit definite definitions here!");
  2556. StringRef MangledName = getMangledName(D);
  2557. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  2558. // We already have a definition, not declaration, with the same mangled name.
  2559. // Emitting of declaration is not required (and actually overwrites emitted
  2560. // definition).
  2561. if (GV && !GV->isDeclaration())
  2562. return;
  2563. // If we have not seen a reference to this variable yet, place it into the
  2564. // deferred declarations table to be emitted if needed later.
  2565. if (!MustBeEmitted(D) && !GV) {
  2566. DeferredDecls[MangledName] = D;
  2567. return;
  2568. }
  2569. // The tentative definition is the only definition.
  2570. EmitGlobalVarDefinition(D);
  2571. }
  2572. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  2573. return Context.toCharUnitsFromBits(
  2574. getDataLayout().getTypeStoreSizeInBits(Ty));
  2575. }
  2576. LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
  2577. LangAS AddrSpace = LangAS::Default;
  2578. if (LangOpts.OpenCL) {
  2579. AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
  2580. assert(AddrSpace == LangAS::opencl_global ||
  2581. AddrSpace == LangAS::opencl_constant ||
  2582. AddrSpace == LangAS::opencl_local ||
  2583. AddrSpace >= LangAS::FirstTargetAddressSpace);
  2584. return AddrSpace;
  2585. }
  2586. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  2587. if (D && D->hasAttr<CUDAConstantAttr>())
  2588. return LangAS::cuda_constant;
  2589. else if (D && D->hasAttr<CUDASharedAttr>())
  2590. return LangAS::cuda_shared;
  2591. else
  2592. return LangAS::cuda_device;
  2593. }
  2594. return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
  2595. }
  2596. template<typename SomeDecl>
  2597. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  2598. llvm::GlobalValue *GV) {
  2599. if (!getLangOpts().CPlusPlus)
  2600. return;
  2601. // Must have 'used' attribute, or else inline assembly can't rely on
  2602. // the name existing.
  2603. if (!D->template hasAttr<UsedAttr>())
  2604. return;
  2605. // Must have internal linkage and an ordinary name.
  2606. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  2607. return;
  2608. // Must be in an extern "C" context. Entities declared directly within
  2609. // a record are not extern "C" even if the record is in such a context.
  2610. const SomeDecl *First = D->getFirstDecl();
  2611. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  2612. return;
  2613. // OK, this is an internal linkage entity inside an extern "C" linkage
  2614. // specification. Make a note of that so we can give it the "expected"
  2615. // mangled name if nothing else is using that name.
  2616. std::pair<StaticExternCMap::iterator, bool> R =
  2617. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  2618. // If we have multiple internal linkage entities with the same name
  2619. // in extern "C" regions, none of them gets that name.
  2620. if (!R.second)
  2621. R.first->second = nullptr;
  2622. }
  2623. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  2624. if (!CGM.supportsCOMDAT())
  2625. return false;
  2626. if (D.hasAttr<SelectAnyAttr>())
  2627. return true;
  2628. GVALinkage Linkage;
  2629. if (auto *VD = dyn_cast<VarDecl>(&D))
  2630. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  2631. else
  2632. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  2633. switch (Linkage) {
  2634. case GVA_Internal:
  2635. case GVA_AvailableExternally:
  2636. case GVA_StrongExternal:
  2637. return false;
  2638. case GVA_DiscardableODR:
  2639. case GVA_StrongODR:
  2640. return true;
  2641. }
  2642. llvm_unreachable("No such linkage");
  2643. }
  2644. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  2645. llvm::GlobalObject &GO) {
  2646. if (!shouldBeInCOMDAT(*this, D))
  2647. return;
  2648. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  2649. }
  2650. /// Pass IsTentative as true if you want to create a tentative definition.
  2651. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  2652. bool IsTentative) {
  2653. // OpenCL global variables of sampler type are translated to function calls,
  2654. // therefore no need to be translated.
  2655. QualType ASTTy = D->getType();
  2656. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  2657. return;
  2658. llvm::Constant *Init = nullptr;
  2659. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2660. bool NeedsGlobalCtor = false;
  2661. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  2662. const VarDecl *InitDecl;
  2663. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2664. Optional<ConstantEmitter> emitter;
  2665. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  2666. // as part of their declaration." Sema has already checked for
  2667. // error cases, so we just need to set Init to UndefValue.
  2668. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  2669. D->hasAttr<CUDASharedAttr>())
  2670. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  2671. else if (!InitExpr) {
  2672. // This is a tentative definition; tentative definitions are
  2673. // implicitly initialized with { 0 }.
  2674. //
  2675. // Note that tentative definitions are only emitted at the end of
  2676. // a translation unit, so they should never have incomplete
  2677. // type. In addition, EmitTentativeDefinition makes sure that we
  2678. // never attempt to emit a tentative definition if a real one
  2679. // exists. A use may still exists, however, so we still may need
  2680. // to do a RAUW.
  2681. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  2682. Init = EmitNullConstant(D->getType());
  2683. } else {
  2684. initializedGlobalDecl = GlobalDecl(D);
  2685. emitter.emplace(*this);
  2686. Init = emitter->tryEmitForInitializer(*InitDecl);
  2687. if (!Init) {
  2688. QualType T = InitExpr->getType();
  2689. if (D->getType()->isReferenceType())
  2690. T = D->getType();
  2691. if (getLangOpts().CPlusPlus) {
  2692. Init = EmitNullConstant(T);
  2693. NeedsGlobalCtor = true;
  2694. } else {
  2695. ErrorUnsupported(D, "static initializer");
  2696. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  2697. }
  2698. } else {
  2699. // We don't need an initializer, so remove the entry for the delayed
  2700. // initializer position (just in case this entry was delayed) if we
  2701. // also don't need to register a destructor.
  2702. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  2703. DelayedCXXInitPosition.erase(D);
  2704. }
  2705. }
  2706. llvm::Type* InitType = Init->getType();
  2707. llvm::Constant *Entry =
  2708. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  2709. // Strip off a bitcast if we got one back.
  2710. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  2711. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  2712. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  2713. // All zero index gep.
  2714. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  2715. Entry = CE->getOperand(0);
  2716. }
  2717. // Entry is now either a Function or GlobalVariable.
  2718. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  2719. // We have a definition after a declaration with the wrong type.
  2720. // We must make a new GlobalVariable* and update everything that used OldGV
  2721. // (a declaration or tentative definition) with the new GlobalVariable*
  2722. // (which will be a definition).
  2723. //
  2724. // This happens if there is a prototype for a global (e.g.
  2725. // "extern int x[];") and then a definition of a different type (e.g.
  2726. // "int x[10];"). This also happens when an initializer has a different type
  2727. // from the type of the global (this happens with unions).
  2728. if (!GV || GV->getType()->getElementType() != InitType ||
  2729. GV->getType()->getAddressSpace() !=
  2730. getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
  2731. // Move the old entry aside so that we'll create a new one.
  2732. Entry->setName(StringRef());
  2733. // Make a new global with the correct type, this is now guaranteed to work.
  2734. GV = cast<llvm::GlobalVariable>(
  2735. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
  2736. // Replace all uses of the old global with the new global
  2737. llvm::Constant *NewPtrForOldDecl =
  2738. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2739. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2740. // Erase the old global, since it is no longer used.
  2741. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  2742. }
  2743. MaybeHandleStaticInExternC(D, GV);
  2744. if (D->hasAttr<AnnotateAttr>())
  2745. AddGlobalAnnotations(D, GV);
  2746. // Set the llvm linkage type as appropriate.
  2747. llvm::GlobalValue::LinkageTypes Linkage =
  2748. getLLVMLinkageVarDefinition(D, GV->isConstant());
  2749. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  2750. // the device. [...]"
  2751. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  2752. // __device__, declares a variable that: [...]
  2753. // Is accessible from all the threads within the grid and from the host
  2754. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  2755. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  2756. if (GV && LangOpts.CUDA) {
  2757. if (LangOpts.CUDAIsDevice) {
  2758. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
  2759. GV->setExternallyInitialized(true);
  2760. } else {
  2761. // Host-side shadows of external declarations of device-side
  2762. // global variables become internal definitions. These have to
  2763. // be internal in order to prevent name conflicts with global
  2764. // host variables with the same name in a different TUs.
  2765. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
  2766. Linkage = llvm::GlobalValue::InternalLinkage;
  2767. // Shadow variables and their properties must be registered
  2768. // with CUDA runtime.
  2769. unsigned Flags = 0;
  2770. if (!D->hasDefinition())
  2771. Flags |= CGCUDARuntime::ExternDeviceVar;
  2772. if (D->hasAttr<CUDAConstantAttr>())
  2773. Flags |= CGCUDARuntime::ConstantDeviceVar;
  2774. getCUDARuntime().registerDeviceVar(*GV, Flags);
  2775. } else if (D->hasAttr<CUDASharedAttr>())
  2776. // __shared__ variables are odd. Shadows do get created, but
  2777. // they are not registered with the CUDA runtime, so they
  2778. // can't really be used to access their device-side
  2779. // counterparts. It's not clear yet whether it's nvcc's bug or
  2780. // a feature, but we've got to do the same for compatibility.
  2781. Linkage = llvm::GlobalValue::InternalLinkage;
  2782. }
  2783. }
  2784. GV->setInitializer(Init);
  2785. if (emitter) emitter->finalize(GV);
  2786. // If it is safe to mark the global 'constant', do so now.
  2787. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  2788. isTypeConstant(D->getType(), true));
  2789. // If it is in a read-only section, mark it 'constant'.
  2790. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  2791. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  2792. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  2793. GV->setConstant(true);
  2794. }
  2795. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2796. // On Darwin, if the normal linkage of a C++ thread_local variable is
  2797. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  2798. // copies within a linkage unit; otherwise, the backing variable has
  2799. // internal linkage and all accesses should just be calls to the
  2800. // Itanium-specified entry point, which has the normal linkage of the
  2801. // variable. This is to preserve the ability to change the implementation
  2802. // behind the scenes.
  2803. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  2804. Context.getTargetInfo().getTriple().isOSDarwin() &&
  2805. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  2806. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  2807. Linkage = llvm::GlobalValue::InternalLinkage;
  2808. GV->setLinkage(Linkage);
  2809. if (D->hasAttr<DLLImportAttr>())
  2810. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  2811. else if (D->hasAttr<DLLExportAttr>())
  2812. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  2813. else
  2814. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  2815. if (Linkage == llvm::GlobalVariable::CommonLinkage) {
  2816. // common vars aren't constant even if declared const.
  2817. GV->setConstant(false);
  2818. // Tentative definition of global variables may be initialized with
  2819. // non-zero null pointers. In this case they should have weak linkage
  2820. // since common linkage must have zero initializer and must not have
  2821. // explicit section therefore cannot have non-zero initial value.
  2822. if (!GV->getInitializer()->isNullValue())
  2823. GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
  2824. }
  2825. setNonAliasAttributes(D, GV);
  2826. if (D->getTLSKind() && !GV->isThreadLocal()) {
  2827. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2828. CXXThreadLocals.push_back(D);
  2829. setTLSMode(GV, *D);
  2830. }
  2831. maybeSetTrivialComdat(*D, *GV);
  2832. // Emit the initializer function if necessary.
  2833. if (NeedsGlobalCtor || NeedsGlobalDtor)
  2834. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  2835. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  2836. // Emit global variable debug information.
  2837. if (CGDebugInfo *DI = getModuleDebugInfo())
  2838. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  2839. DI->EmitGlobalVariable(GV, D);
  2840. }
  2841. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  2842. CodeGenModule &CGM, const VarDecl *D,
  2843. bool NoCommon) {
  2844. // Don't give variables common linkage if -fno-common was specified unless it
  2845. // was overridden by a NoCommon attribute.
  2846. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  2847. return true;
  2848. // C11 6.9.2/2:
  2849. // A declaration of an identifier for an object that has file scope without
  2850. // an initializer, and without a storage-class specifier or with the
  2851. // storage-class specifier static, constitutes a tentative definition.
  2852. if (D->getInit() || D->hasExternalStorage())
  2853. return true;
  2854. // A variable cannot be both common and exist in a section.
  2855. if (D->hasAttr<SectionAttr>())
  2856. return true;
  2857. // A variable cannot be both common and exist in a section.
  2858. // We dont try to determine which is the right section in the front-end.
  2859. // If no specialized section name is applicable, it will resort to default.
  2860. if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
  2861. D->hasAttr<PragmaClangDataSectionAttr>() ||
  2862. D->hasAttr<PragmaClangRodataSectionAttr>())
  2863. return true;
  2864. // Thread local vars aren't considered common linkage.
  2865. if (D->getTLSKind())
  2866. return true;
  2867. // Tentative definitions marked with WeakImportAttr are true definitions.
  2868. if (D->hasAttr<WeakImportAttr>())
  2869. return true;
  2870. // A variable cannot be both common and exist in a comdat.
  2871. if (shouldBeInCOMDAT(CGM, *D))
  2872. return true;
  2873. // Declarations with a required alignment do not have common linkage in MSVC
  2874. // mode.
  2875. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2876. if (D->hasAttr<AlignedAttr>())
  2877. return true;
  2878. QualType VarType = D->getType();
  2879. if (Context.isAlignmentRequired(VarType))
  2880. return true;
  2881. if (const auto *RT = VarType->getAs<RecordType>()) {
  2882. const RecordDecl *RD = RT->getDecl();
  2883. for (const FieldDecl *FD : RD->fields()) {
  2884. if (FD->isBitField())
  2885. continue;
  2886. if (FD->hasAttr<AlignedAttr>())
  2887. return true;
  2888. if (Context.isAlignmentRequired(FD->getType()))
  2889. return true;
  2890. }
  2891. }
  2892. }
  2893. return false;
  2894. }
  2895. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  2896. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  2897. if (Linkage == GVA_Internal)
  2898. return llvm::Function::InternalLinkage;
  2899. if (D->hasAttr<WeakAttr>()) {
  2900. if (IsConstantVariable)
  2901. return llvm::GlobalVariable::WeakODRLinkage;
  2902. else
  2903. return llvm::GlobalVariable::WeakAnyLinkage;
  2904. }
  2905. // We are guaranteed to have a strong definition somewhere else,
  2906. // so we can use available_externally linkage.
  2907. if (Linkage == GVA_AvailableExternally)
  2908. return llvm::GlobalValue::AvailableExternallyLinkage;
  2909. // Note that Apple's kernel linker doesn't support symbol
  2910. // coalescing, so we need to avoid linkonce and weak linkages there.
  2911. // Normally, this means we just map to internal, but for explicit
  2912. // instantiations we'll map to external.
  2913. // In C++, the compiler has to emit a definition in every translation unit
  2914. // that references the function. We should use linkonce_odr because
  2915. // a) if all references in this translation unit are optimized away, we
  2916. // don't need to codegen it. b) if the function persists, it needs to be
  2917. // merged with other definitions. c) C++ has the ODR, so we know the
  2918. // definition is dependable.
  2919. if (Linkage == GVA_DiscardableODR)
  2920. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  2921. : llvm::Function::InternalLinkage;
  2922. // An explicit instantiation of a template has weak linkage, since
  2923. // explicit instantiations can occur in multiple translation units
  2924. // and must all be equivalent. However, we are not allowed to
  2925. // throw away these explicit instantiations.
  2926. //
  2927. // We don't currently support CUDA device code spread out across multiple TUs,
  2928. // so say that CUDA templates are either external (for kernels) or internal.
  2929. // This lets llvm perform aggressive inter-procedural optimizations.
  2930. if (Linkage == GVA_StrongODR) {
  2931. if (Context.getLangOpts().AppleKext)
  2932. return llvm::Function::ExternalLinkage;
  2933. if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
  2934. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  2935. : llvm::Function::InternalLinkage;
  2936. return llvm::Function::WeakODRLinkage;
  2937. }
  2938. // C++ doesn't have tentative definitions and thus cannot have common
  2939. // linkage.
  2940. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  2941. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  2942. CodeGenOpts.NoCommon))
  2943. return llvm::GlobalVariable::CommonLinkage;
  2944. // selectany symbols are externally visible, so use weak instead of
  2945. // linkonce. MSVC optimizes away references to const selectany globals, so
  2946. // all definitions should be the same and ODR linkage should be used.
  2947. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  2948. if (D->hasAttr<SelectAnyAttr>())
  2949. return llvm::GlobalVariable::WeakODRLinkage;
  2950. // Otherwise, we have strong external linkage.
  2951. assert(Linkage == GVA_StrongExternal);
  2952. return llvm::GlobalVariable::ExternalLinkage;
  2953. }
  2954. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  2955. const VarDecl *VD, bool IsConstant) {
  2956. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  2957. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  2958. }
  2959. /// Replace the uses of a function that was declared with a non-proto type.
  2960. /// We want to silently drop extra arguments from call sites
  2961. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  2962. llvm::Function *newFn) {
  2963. // Fast path.
  2964. if (old->use_empty()) return;
  2965. llvm::Type *newRetTy = newFn->getReturnType();
  2966. SmallVector<llvm::Value*, 4> newArgs;
  2967. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  2968. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  2969. ui != ue; ) {
  2970. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  2971. llvm::User *user = use->getUser();
  2972. // Recognize and replace uses of bitcasts. Most calls to
  2973. // unprototyped functions will use bitcasts.
  2974. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  2975. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  2976. replaceUsesOfNonProtoConstant(bitcast, newFn);
  2977. continue;
  2978. }
  2979. // Recognize calls to the function.
  2980. llvm::CallSite callSite(user);
  2981. if (!callSite) continue;
  2982. if (!callSite.isCallee(&*use)) continue;
  2983. // If the return types don't match exactly, then we can't
  2984. // transform this call unless it's dead.
  2985. if (callSite->getType() != newRetTy && !callSite->use_empty())
  2986. continue;
  2987. // Get the call site's attribute list.
  2988. SmallVector<llvm::AttributeSet, 8> newArgAttrs;
  2989. llvm::AttributeList oldAttrs = callSite.getAttributes();
  2990. // If the function was passed too few arguments, don't transform.
  2991. unsigned newNumArgs = newFn->arg_size();
  2992. if (callSite.arg_size() < newNumArgs) continue;
  2993. // If extra arguments were passed, we silently drop them.
  2994. // If any of the types mismatch, we don't transform.
  2995. unsigned argNo = 0;
  2996. bool dontTransform = false;
  2997. for (llvm::Argument &A : newFn->args()) {
  2998. if (callSite.getArgument(argNo)->getType() != A.getType()) {
  2999. dontTransform = true;
  3000. break;
  3001. }
  3002. // Add any parameter attributes.
  3003. newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
  3004. argNo++;
  3005. }
  3006. if (dontTransform)
  3007. continue;
  3008. // Okay, we can transform this. Create the new call instruction and copy
  3009. // over the required information.
  3010. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  3011. // Copy over any operand bundles.
  3012. callSite.getOperandBundlesAsDefs(newBundles);
  3013. llvm::CallSite newCall;
  3014. if (callSite.isCall()) {
  3015. newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
  3016. callSite.getInstruction());
  3017. } else {
  3018. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  3019. newCall = llvm::InvokeInst::Create(newFn,
  3020. oldInvoke->getNormalDest(),
  3021. oldInvoke->getUnwindDest(),
  3022. newArgs, newBundles, "",
  3023. callSite.getInstruction());
  3024. }
  3025. newArgs.clear(); // for the next iteration
  3026. if (!newCall->getType()->isVoidTy())
  3027. newCall->takeName(callSite.getInstruction());
  3028. newCall.setAttributes(llvm::AttributeList::get(
  3029. newFn->getContext(), oldAttrs.getFnAttributes(),
  3030. oldAttrs.getRetAttributes(), newArgAttrs));
  3031. newCall.setCallingConv(callSite.getCallingConv());
  3032. // Finally, remove the old call, replacing any uses with the new one.
  3033. if (!callSite->use_empty())
  3034. callSite->replaceAllUsesWith(newCall.getInstruction());
  3035. // Copy debug location attached to CI.
  3036. if (callSite->getDebugLoc())
  3037. newCall->setDebugLoc(callSite->getDebugLoc());
  3038. callSite->eraseFromParent();
  3039. }
  3040. }
  3041. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  3042. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  3043. /// existing call uses of the old function in the module, this adjusts them to
  3044. /// call the new function directly.
  3045. ///
  3046. /// This is not just a cleanup: the always_inline pass requires direct calls to
  3047. /// functions to be able to inline them. If there is a bitcast in the way, it
  3048. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  3049. /// run at -O0.
  3050. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  3051. llvm::Function *NewFn) {
  3052. // If we're redefining a global as a function, don't transform it.
  3053. if (!isa<llvm::Function>(Old)) return;
  3054. replaceUsesOfNonProtoConstant(Old, NewFn);
  3055. }
  3056. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  3057. auto DK = VD->isThisDeclarationADefinition();
  3058. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  3059. return;
  3060. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  3061. // If we have a definition, this might be a deferred decl. If the
  3062. // instantiation is explicit, make sure we emit it at the end.
  3063. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  3064. GetAddrOfGlobalVar(VD);
  3065. EmitTopLevelDecl(VD);
  3066. }
  3067. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  3068. llvm::GlobalValue *GV) {
  3069. const auto *D = cast<FunctionDecl>(GD.getDecl());
  3070. // Compute the function info and LLVM type.
  3071. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  3072. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  3073. // Get or create the prototype for the function.
  3074. if (!GV || (GV->getType()->getElementType() != Ty))
  3075. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  3076. /*DontDefer=*/true,
  3077. ForDefinition));
  3078. // Already emitted.
  3079. if (!GV->isDeclaration())
  3080. return;
  3081. // We need to set linkage and visibility on the function before
  3082. // generating code for it because various parts of IR generation
  3083. // want to propagate this information down (e.g. to local static
  3084. // declarations).
  3085. auto *Fn = cast<llvm::Function>(GV);
  3086. setFunctionLinkage(GD, Fn);
  3087. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  3088. setGVProperties(Fn, GD);
  3089. MaybeHandleStaticInExternC(D, Fn);
  3090. maybeSetTrivialComdat(*D, *Fn);
  3091. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  3092. setNonAliasAttributes(GD, Fn);
  3093. SetLLVMFunctionAttributesForDefinition(D, Fn);
  3094. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  3095. AddGlobalCtor(Fn, CA->getPriority());
  3096. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  3097. AddGlobalDtor(Fn, DA->getPriority());
  3098. if (D->hasAttr<AnnotateAttr>())
  3099. AddGlobalAnnotations(D, Fn);
  3100. }
  3101. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  3102. const auto *D = cast<ValueDecl>(GD.getDecl());
  3103. const AliasAttr *AA = D->getAttr<AliasAttr>();
  3104. assert(AA && "Not an alias?");
  3105. StringRef MangledName = getMangledName(GD);
  3106. if (AA->getAliasee() == MangledName) {
  3107. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3108. return;
  3109. }
  3110. // If there is a definition in the module, then it wins over the alias.
  3111. // This is dubious, but allow it to be safe. Just ignore the alias.
  3112. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3113. if (Entry && !Entry->isDeclaration())
  3114. return;
  3115. Aliases.push_back(GD);
  3116. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3117. // Create a reference to the named value. This ensures that it is emitted
  3118. // if a deferred decl.
  3119. llvm::Constant *Aliasee;
  3120. if (isa<llvm::FunctionType>(DeclTy))
  3121. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  3122. /*ForVTable=*/false);
  3123. else
  3124. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  3125. llvm::PointerType::getUnqual(DeclTy),
  3126. /*D=*/nullptr);
  3127. // Create the new alias itself, but don't set a name yet.
  3128. auto *GA = llvm::GlobalAlias::create(
  3129. DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  3130. if (Entry) {
  3131. if (GA->getAliasee() == Entry) {
  3132. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3133. return;
  3134. }
  3135. assert(Entry->isDeclaration());
  3136. // If there is a declaration in the module, then we had an extern followed
  3137. // by the alias, as in:
  3138. // extern int test6();
  3139. // ...
  3140. // int test6() __attribute__((alias("test7")));
  3141. //
  3142. // Remove it and replace uses of it with the alias.
  3143. GA->takeName(Entry);
  3144. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  3145. Entry->getType()));
  3146. Entry->eraseFromParent();
  3147. } else {
  3148. GA->setName(MangledName);
  3149. }
  3150. // Set attributes which are particular to an alias; this is a
  3151. // specialization of the attributes which may be set on a global
  3152. // variable/function.
  3153. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  3154. D->isWeakImported()) {
  3155. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  3156. }
  3157. if (const auto *VD = dyn_cast<VarDecl>(D))
  3158. if (VD->getTLSKind())
  3159. setTLSMode(GA, *VD);
  3160. SetCommonAttributes(GD, GA);
  3161. }
  3162. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  3163. const auto *D = cast<ValueDecl>(GD.getDecl());
  3164. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  3165. assert(IFA && "Not an ifunc?");
  3166. StringRef MangledName = getMangledName(GD);
  3167. if (IFA->getResolver() == MangledName) {
  3168. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3169. return;
  3170. }
  3171. // Report an error if some definition overrides ifunc.
  3172. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3173. if (Entry && !Entry->isDeclaration()) {
  3174. GlobalDecl OtherGD;
  3175. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  3176. DiagnosedConflictingDefinitions.insert(GD).second) {
  3177. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
  3178. Diags.Report(OtherGD.getDecl()->getLocation(),
  3179. diag::note_previous_definition);
  3180. }
  3181. return;
  3182. }
  3183. Aliases.push_back(GD);
  3184. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3185. llvm::Constant *Resolver =
  3186. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  3187. /*ForVTable=*/false);
  3188. llvm::GlobalIFunc *GIF =
  3189. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  3190. "", Resolver, &getModule());
  3191. if (Entry) {
  3192. if (GIF->getResolver() == Entry) {
  3193. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3194. return;
  3195. }
  3196. assert(Entry->isDeclaration());
  3197. // If there is a declaration in the module, then we had an extern followed
  3198. // by the ifunc, as in:
  3199. // extern int test();
  3200. // ...
  3201. // int test() __attribute__((ifunc("resolver")));
  3202. //
  3203. // Remove it and replace uses of it with the ifunc.
  3204. GIF->takeName(Entry);
  3205. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  3206. Entry->getType()));
  3207. Entry->eraseFromParent();
  3208. } else
  3209. GIF->setName(MangledName);
  3210. SetCommonAttributes(GD, GIF);
  3211. }
  3212. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  3213. ArrayRef<llvm::Type*> Tys) {
  3214. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  3215. Tys);
  3216. }
  3217. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  3218. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  3219. const StringLiteral *Literal, bool TargetIsLSB,
  3220. bool &IsUTF16, unsigned &StringLength) {
  3221. StringRef String = Literal->getString();
  3222. unsigned NumBytes = String.size();
  3223. // Check for simple case.
  3224. if (!Literal->containsNonAsciiOrNull()) {
  3225. StringLength = NumBytes;
  3226. return *Map.insert(std::make_pair(String, nullptr)).first;
  3227. }
  3228. // Otherwise, convert the UTF8 literals into a string of shorts.
  3229. IsUTF16 = true;
  3230. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  3231. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3232. llvm::UTF16 *ToPtr = &ToBuf[0];
  3233. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3234. ToPtr + NumBytes, llvm::strictConversion);
  3235. // ConvertUTF8toUTF16 returns the length in ToPtr.
  3236. StringLength = ToPtr - &ToBuf[0];
  3237. // Add an explicit null.
  3238. *ToPtr = 0;
  3239. return *Map.insert(std::make_pair(
  3240. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  3241. (StringLength + 1) * 2),
  3242. nullptr)).first;
  3243. }
  3244. ConstantAddress
  3245. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  3246. unsigned StringLength = 0;
  3247. bool isUTF16 = false;
  3248. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  3249. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  3250. getDataLayout().isLittleEndian(), isUTF16,
  3251. StringLength);
  3252. if (auto *C = Entry.second)
  3253. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  3254. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  3255. llvm::Constant *Zeros[] = { Zero, Zero };
  3256. // If we don't already have it, get __CFConstantStringClassReference.
  3257. if (!CFConstantStringClassRef) {
  3258. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  3259. Ty = llvm::ArrayType::get(Ty, 0);
  3260. llvm::Constant *GV =
  3261. CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
  3262. if (getTriple().isOSBinFormatCOFF()) {
  3263. IdentifierInfo &II = getContext().Idents.get(GV->getName());
  3264. TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
  3265. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  3266. llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
  3267. const VarDecl *VD = nullptr;
  3268. for (const auto &Result : DC->lookup(&II))
  3269. if ((VD = dyn_cast<VarDecl>(Result)))
  3270. break;
  3271. if (!VD || !VD->hasAttr<DLLExportAttr>()) {
  3272. CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  3273. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3274. } else {
  3275. CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  3276. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3277. }
  3278. }
  3279. // Decay array -> ptr
  3280. CFConstantStringClassRef =
  3281. llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  3282. }
  3283. QualType CFTy = getContext().getCFConstantStringType();
  3284. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  3285. ConstantInitBuilder Builder(*this);
  3286. auto Fields = Builder.beginStruct(STy);
  3287. // Class pointer.
  3288. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  3289. // Flags.
  3290. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  3291. // String pointer.
  3292. llvm::Constant *C = nullptr;
  3293. if (isUTF16) {
  3294. auto Arr = llvm::makeArrayRef(
  3295. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  3296. Entry.first().size() / 2);
  3297. C = llvm::ConstantDataArray::get(VMContext, Arr);
  3298. } else {
  3299. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  3300. }
  3301. // Note: -fwritable-strings doesn't make the backing store strings of
  3302. // CFStrings writable. (See <rdar://problem/10657500>)
  3303. auto *GV =
  3304. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  3305. llvm::GlobalValue::PrivateLinkage, C, ".str");
  3306. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3307. // Don't enforce the target's minimum global alignment, since the only use
  3308. // of the string is via this class initializer.
  3309. CharUnits Align = isUTF16
  3310. ? getContext().getTypeAlignInChars(getContext().ShortTy)
  3311. : getContext().getTypeAlignInChars(getContext().CharTy);
  3312. GV->setAlignment(Align.getQuantity());
  3313. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  3314. // Without it LLVM can merge the string with a non unnamed_addr one during
  3315. // LTO. Doing that changes the section it ends in, which surprises ld64.
  3316. if (getTriple().isOSBinFormatMachO())
  3317. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  3318. : "__TEXT,__cstring,cstring_literals");
  3319. // String.
  3320. llvm::Constant *Str =
  3321. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  3322. if (isUTF16)
  3323. // Cast the UTF16 string to the correct type.
  3324. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  3325. Fields.add(Str);
  3326. // String length.
  3327. auto Ty = getTypes().ConvertType(getContext().LongTy);
  3328. Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
  3329. CharUnits Alignment = getPointerAlign();
  3330. // The struct.
  3331. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  3332. /*isConstant=*/false,
  3333. llvm::GlobalVariable::PrivateLinkage);
  3334. switch (getTriple().getObjectFormat()) {
  3335. case llvm::Triple::UnknownObjectFormat:
  3336. llvm_unreachable("unknown file format");
  3337. case llvm::Triple::COFF:
  3338. case llvm::Triple::ELF:
  3339. case llvm::Triple::Wasm:
  3340. GV->setSection("cfstring");
  3341. break;
  3342. case llvm::Triple::MachO:
  3343. GV->setSection("__DATA,__cfstring");
  3344. break;
  3345. }
  3346. Entry.second = GV;
  3347. return ConstantAddress(GV, Alignment);
  3348. }
  3349. bool CodeGenModule::getExpressionLocationsEnabled() const {
  3350. return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
  3351. }
  3352. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  3353. if (ObjCFastEnumerationStateType.isNull()) {
  3354. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  3355. D->startDefinition();
  3356. QualType FieldTypes[] = {
  3357. Context.UnsignedLongTy,
  3358. Context.getPointerType(Context.getObjCIdType()),
  3359. Context.getPointerType(Context.UnsignedLongTy),
  3360. Context.getConstantArrayType(Context.UnsignedLongTy,
  3361. llvm::APInt(32, 5), ArrayType::Normal, 0)
  3362. };
  3363. for (size_t i = 0; i < 4; ++i) {
  3364. FieldDecl *Field = FieldDecl::Create(Context,
  3365. D,
  3366. SourceLocation(),
  3367. SourceLocation(), nullptr,
  3368. FieldTypes[i], /*TInfo=*/nullptr,
  3369. /*BitWidth=*/nullptr,
  3370. /*Mutable=*/false,
  3371. ICIS_NoInit);
  3372. Field->setAccess(AS_public);
  3373. D->addDecl(Field);
  3374. }
  3375. D->completeDefinition();
  3376. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  3377. }
  3378. return ObjCFastEnumerationStateType;
  3379. }
  3380. llvm::Constant *
  3381. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  3382. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  3383. // Don't emit it as the address of the string, emit the string data itself
  3384. // as an inline array.
  3385. if (E->getCharByteWidth() == 1) {
  3386. SmallString<64> Str(E->getString());
  3387. // Resize the string to the right size, which is indicated by its type.
  3388. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  3389. Str.resize(CAT->getSize().getZExtValue());
  3390. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  3391. }
  3392. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  3393. llvm::Type *ElemTy = AType->getElementType();
  3394. unsigned NumElements = AType->getNumElements();
  3395. // Wide strings have either 2-byte or 4-byte elements.
  3396. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  3397. SmallVector<uint16_t, 32> Elements;
  3398. Elements.reserve(NumElements);
  3399. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3400. Elements.push_back(E->getCodeUnit(i));
  3401. Elements.resize(NumElements);
  3402. return llvm::ConstantDataArray::get(VMContext, Elements);
  3403. }
  3404. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  3405. SmallVector<uint32_t, 32> Elements;
  3406. Elements.reserve(NumElements);
  3407. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3408. Elements.push_back(E->getCodeUnit(i));
  3409. Elements.resize(NumElements);
  3410. return llvm::ConstantDataArray::get(VMContext, Elements);
  3411. }
  3412. static llvm::GlobalVariable *
  3413. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  3414. CodeGenModule &CGM, StringRef GlobalName,
  3415. CharUnits Alignment) {
  3416. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  3417. unsigned AddrSpace = 0;
  3418. if (CGM.getLangOpts().OpenCL)
  3419. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  3420. llvm::Module &M = CGM.getModule();
  3421. // Create a global variable for this string
  3422. auto *GV = new llvm::GlobalVariable(
  3423. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  3424. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  3425. GV->setAlignment(Alignment.getQuantity());
  3426. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3427. if (GV->isWeakForLinker()) {
  3428. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  3429. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  3430. }
  3431. return GV;
  3432. }
  3433. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  3434. /// constant array for the given string literal.
  3435. ConstantAddress
  3436. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  3437. StringRef Name) {
  3438. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  3439. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  3440. llvm::GlobalVariable **Entry = nullptr;
  3441. if (!LangOpts.WritableStrings) {
  3442. Entry = &ConstantStringMap[C];
  3443. if (auto GV = *Entry) {
  3444. if (Alignment.getQuantity() > GV->getAlignment())
  3445. GV->setAlignment(Alignment.getQuantity());
  3446. return ConstantAddress(GV, Alignment);
  3447. }
  3448. }
  3449. SmallString<256> MangledNameBuffer;
  3450. StringRef GlobalVariableName;
  3451. llvm::GlobalValue::LinkageTypes LT;
  3452. // Mangle the string literal if the ABI allows for it. However, we cannot
  3453. // do this if we are compiling with ASan or -fwritable-strings because they
  3454. // rely on strings having normal linkage.
  3455. if (!LangOpts.WritableStrings &&
  3456. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  3457. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  3458. llvm::raw_svector_ostream Out(MangledNameBuffer);
  3459. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  3460. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  3461. GlobalVariableName = MangledNameBuffer;
  3462. } else {
  3463. LT = llvm::GlobalValue::PrivateLinkage;
  3464. GlobalVariableName = Name;
  3465. }
  3466. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  3467. if (Entry)
  3468. *Entry = GV;
  3469. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  3470. QualType());
  3471. return ConstantAddress(GV, Alignment);
  3472. }
  3473. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  3474. /// array for the given ObjCEncodeExpr node.
  3475. ConstantAddress
  3476. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  3477. std::string Str;
  3478. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  3479. return GetAddrOfConstantCString(Str);
  3480. }
  3481. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  3482. /// the literal and a terminating '\0' character.
  3483. /// The result has pointer to array type.
  3484. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  3485. const std::string &Str, const char *GlobalName) {
  3486. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  3487. CharUnits Alignment =
  3488. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  3489. llvm::Constant *C =
  3490. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  3491. // Don't share any string literals if strings aren't constant.
  3492. llvm::GlobalVariable **Entry = nullptr;
  3493. if (!LangOpts.WritableStrings) {
  3494. Entry = &ConstantStringMap[C];
  3495. if (auto GV = *Entry) {
  3496. if (Alignment.getQuantity() > GV->getAlignment())
  3497. GV->setAlignment(Alignment.getQuantity());
  3498. return ConstantAddress(GV, Alignment);
  3499. }
  3500. }
  3501. // Get the default prefix if a name wasn't specified.
  3502. if (!GlobalName)
  3503. GlobalName = ".str";
  3504. // Create a global variable for this.
  3505. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  3506. GlobalName, Alignment);
  3507. if (Entry)
  3508. *Entry = GV;
  3509. return ConstantAddress(GV, Alignment);
  3510. }
  3511. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  3512. const MaterializeTemporaryExpr *E, const Expr *Init) {
  3513. assert((E->getStorageDuration() == SD_Static ||
  3514. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  3515. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  3516. // If we're not materializing a subobject of the temporary, keep the
  3517. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  3518. QualType MaterializedType = Init->getType();
  3519. if (Init == E->GetTemporaryExpr())
  3520. MaterializedType = E->getType();
  3521. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  3522. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  3523. return ConstantAddress(Slot, Align);
  3524. // FIXME: If an externally-visible declaration extends multiple temporaries,
  3525. // we need to give each temporary the same name in every translation unit (and
  3526. // we also need to make the temporaries externally-visible).
  3527. SmallString<256> Name;
  3528. llvm::raw_svector_ostream Out(Name);
  3529. getCXXABI().getMangleContext().mangleReferenceTemporary(
  3530. VD, E->getManglingNumber(), Out);
  3531. APValue *Value = nullptr;
  3532. if (E->getStorageDuration() == SD_Static) {
  3533. // We might have a cached constant initializer for this temporary. Note
  3534. // that this might have a different value from the value computed by
  3535. // evaluating the initializer if the surrounding constant expression
  3536. // modifies the temporary.
  3537. Value = getContext().getMaterializedTemporaryValue(E, false);
  3538. if (Value && Value->isUninit())
  3539. Value = nullptr;
  3540. }
  3541. // Try evaluating it now, it might have a constant initializer.
  3542. Expr::EvalResult EvalResult;
  3543. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  3544. !EvalResult.hasSideEffects())
  3545. Value = &EvalResult.Val;
  3546. LangAS AddrSpace =
  3547. VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
  3548. Optional<ConstantEmitter> emitter;
  3549. llvm::Constant *InitialValue = nullptr;
  3550. bool Constant = false;
  3551. llvm::Type *Type;
  3552. if (Value) {
  3553. // The temporary has a constant initializer, use it.
  3554. emitter.emplace(*this);
  3555. InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
  3556. MaterializedType);
  3557. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  3558. Type = InitialValue->getType();
  3559. } else {
  3560. // No initializer, the initialization will be provided when we
  3561. // initialize the declaration which performed lifetime extension.
  3562. Type = getTypes().ConvertTypeForMem(MaterializedType);
  3563. }
  3564. // Create a global variable for this lifetime-extended temporary.
  3565. llvm::GlobalValue::LinkageTypes Linkage =
  3566. getLLVMLinkageVarDefinition(VD, Constant);
  3567. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  3568. const VarDecl *InitVD;
  3569. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  3570. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  3571. // Temporaries defined inside a class get linkonce_odr linkage because the
  3572. // class can be defined in multipe translation units.
  3573. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  3574. } else {
  3575. // There is no need for this temporary to have external linkage if the
  3576. // VarDecl has external linkage.
  3577. Linkage = llvm::GlobalVariable::InternalLinkage;
  3578. }
  3579. }
  3580. auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
  3581. auto *GV = new llvm::GlobalVariable(
  3582. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  3583. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  3584. if (emitter) emitter->finalize(GV);
  3585. setGVProperties(GV, VD);
  3586. GV->setAlignment(Align.getQuantity());
  3587. if (supportsCOMDAT() && GV->isWeakForLinker())
  3588. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  3589. if (VD->getTLSKind())
  3590. setTLSMode(GV, *VD);
  3591. llvm::Constant *CV = GV;
  3592. if (AddrSpace != LangAS::Default)
  3593. CV = getTargetCodeGenInfo().performAddrSpaceCast(
  3594. *this, GV, AddrSpace, LangAS::Default,
  3595. Type->getPointerTo(
  3596. getContext().getTargetAddressSpace(LangAS::Default)));
  3597. MaterializedGlobalTemporaryMap[E] = CV;
  3598. return ConstantAddress(CV, Align);
  3599. }
  3600. /// EmitObjCPropertyImplementations - Emit information for synthesized
  3601. /// properties for an implementation.
  3602. void CodeGenModule::EmitObjCPropertyImplementations(const
  3603. ObjCImplementationDecl *D) {
  3604. for (const auto *PID : D->property_impls()) {
  3605. // Dynamic is just for type-checking.
  3606. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  3607. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  3608. // Determine which methods need to be implemented, some may have
  3609. // been overridden. Note that ::isPropertyAccessor is not the method
  3610. // we want, that just indicates if the decl came from a
  3611. // property. What we want to know is if the method is defined in
  3612. // this implementation.
  3613. if (!D->getInstanceMethod(PD->getGetterName()))
  3614. CodeGenFunction(*this).GenerateObjCGetter(
  3615. const_cast<ObjCImplementationDecl *>(D), PID);
  3616. if (!PD->isReadOnly() &&
  3617. !D->getInstanceMethod(PD->getSetterName()))
  3618. CodeGenFunction(*this).GenerateObjCSetter(
  3619. const_cast<ObjCImplementationDecl *>(D), PID);
  3620. }
  3621. }
  3622. }
  3623. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  3624. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  3625. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  3626. ivar; ivar = ivar->getNextIvar())
  3627. if (ivar->getType().isDestructedType())
  3628. return true;
  3629. return false;
  3630. }
  3631. static bool AllTrivialInitializers(CodeGenModule &CGM,
  3632. ObjCImplementationDecl *D) {
  3633. CodeGenFunction CGF(CGM);
  3634. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  3635. E = D->init_end(); B != E; ++B) {
  3636. CXXCtorInitializer *CtorInitExp = *B;
  3637. Expr *Init = CtorInitExp->getInit();
  3638. if (!CGF.isTrivialInitializer(Init))
  3639. return false;
  3640. }
  3641. return true;
  3642. }
  3643. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  3644. /// for an implementation.
  3645. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  3646. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  3647. if (needsDestructMethod(D)) {
  3648. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  3649. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3650. ObjCMethodDecl *DTORMethod =
  3651. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  3652. cxxSelector, getContext().VoidTy, nullptr, D,
  3653. /*isInstance=*/true, /*isVariadic=*/false,
  3654. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  3655. /*isDefined=*/false, ObjCMethodDecl::Required);
  3656. D->addInstanceMethod(DTORMethod);
  3657. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  3658. D->setHasDestructors(true);
  3659. }
  3660. // If the implementation doesn't have any ivar initializers, we don't need
  3661. // a .cxx_construct.
  3662. if (D->getNumIvarInitializers() == 0 ||
  3663. AllTrivialInitializers(*this, D))
  3664. return;
  3665. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  3666. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3667. // The constructor returns 'self'.
  3668. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  3669. D->getLocation(),
  3670. D->getLocation(),
  3671. cxxSelector,
  3672. getContext().getObjCIdType(),
  3673. nullptr, D, /*isInstance=*/true,
  3674. /*isVariadic=*/false,
  3675. /*isPropertyAccessor=*/true,
  3676. /*isImplicitlyDeclared=*/true,
  3677. /*isDefined=*/false,
  3678. ObjCMethodDecl::Required);
  3679. D->addInstanceMethod(CTORMethod);
  3680. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  3681. D->setHasNonZeroConstructors(true);
  3682. }
  3683. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  3684. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  3685. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  3686. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  3687. ErrorUnsupported(LSD, "linkage spec");
  3688. return;
  3689. }
  3690. EmitDeclContext(LSD);
  3691. }
  3692. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  3693. for (auto *I : DC->decls()) {
  3694. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  3695. // are themselves considered "top-level", so EmitTopLevelDecl on an
  3696. // ObjCImplDecl does not recursively visit them. We need to do that in
  3697. // case they're nested inside another construct (LinkageSpecDecl /
  3698. // ExportDecl) that does stop them from being considered "top-level".
  3699. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  3700. for (auto *M : OID->methods())
  3701. EmitTopLevelDecl(M);
  3702. }
  3703. EmitTopLevelDecl(I);
  3704. }
  3705. }
  3706. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  3707. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  3708. // Ignore dependent declarations.
  3709. if (D->isTemplated())
  3710. return;
  3711. switch (D->getKind()) {
  3712. case Decl::CXXConversion:
  3713. case Decl::CXXMethod:
  3714. case Decl::Function:
  3715. EmitGlobal(cast<FunctionDecl>(D));
  3716. // Always provide some coverage mapping
  3717. // even for the functions that aren't emitted.
  3718. AddDeferredUnusedCoverageMapping(D);
  3719. break;
  3720. case Decl::CXXDeductionGuide:
  3721. // Function-like, but does not result in code emission.
  3722. break;
  3723. case Decl::Var:
  3724. case Decl::Decomposition:
  3725. case Decl::VarTemplateSpecialization:
  3726. EmitGlobal(cast<VarDecl>(D));
  3727. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  3728. for (auto *B : DD->bindings())
  3729. if (auto *HD = B->getHoldingVar())
  3730. EmitGlobal(HD);
  3731. break;
  3732. // Indirect fields from global anonymous structs and unions can be
  3733. // ignored; only the actual variable requires IR gen support.
  3734. case Decl::IndirectField:
  3735. break;
  3736. // C++ Decls
  3737. case Decl::Namespace:
  3738. EmitDeclContext(cast<NamespaceDecl>(D));
  3739. break;
  3740. case Decl::ClassTemplateSpecialization: {
  3741. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  3742. if (DebugInfo &&
  3743. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  3744. Spec->hasDefinition())
  3745. DebugInfo->completeTemplateDefinition(*Spec);
  3746. } LLVM_FALLTHROUGH;
  3747. case Decl::CXXRecord:
  3748. if (DebugInfo) {
  3749. if (auto *ES = D->getASTContext().getExternalSource())
  3750. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  3751. DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
  3752. }
  3753. // Emit any static data members, they may be definitions.
  3754. for (auto *I : cast<CXXRecordDecl>(D)->decls())
  3755. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  3756. EmitTopLevelDecl(I);
  3757. break;
  3758. // No code generation needed.
  3759. case Decl::UsingShadow:
  3760. case Decl::ClassTemplate:
  3761. case Decl::VarTemplate:
  3762. case Decl::VarTemplatePartialSpecialization:
  3763. case Decl::FunctionTemplate:
  3764. case Decl::TypeAliasTemplate:
  3765. case Decl::Block:
  3766. case Decl::Empty:
  3767. break;
  3768. case Decl::Using: // using X; [C++]
  3769. if (CGDebugInfo *DI = getModuleDebugInfo())
  3770. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  3771. return;
  3772. case Decl::NamespaceAlias:
  3773. if (CGDebugInfo *DI = getModuleDebugInfo())
  3774. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  3775. return;
  3776. case Decl::UsingDirective: // using namespace X; [C++]
  3777. if (CGDebugInfo *DI = getModuleDebugInfo())
  3778. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  3779. return;
  3780. case Decl::CXXConstructor:
  3781. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  3782. break;
  3783. case Decl::CXXDestructor:
  3784. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  3785. break;
  3786. case Decl::StaticAssert:
  3787. // Nothing to do.
  3788. break;
  3789. // Objective-C Decls
  3790. // Forward declarations, no (immediate) code generation.
  3791. case Decl::ObjCInterface:
  3792. case Decl::ObjCCategory:
  3793. break;
  3794. case Decl::ObjCProtocol: {
  3795. auto *Proto = cast<ObjCProtocolDecl>(D);
  3796. if (Proto->isThisDeclarationADefinition())
  3797. ObjCRuntime->GenerateProtocol(Proto);
  3798. break;
  3799. }
  3800. case Decl::ObjCCategoryImpl:
  3801. // Categories have properties but don't support synthesize so we
  3802. // can ignore them here.
  3803. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  3804. break;
  3805. case Decl::ObjCImplementation: {
  3806. auto *OMD = cast<ObjCImplementationDecl>(D);
  3807. EmitObjCPropertyImplementations(OMD);
  3808. EmitObjCIvarInitializations(OMD);
  3809. ObjCRuntime->GenerateClass(OMD);
  3810. // Emit global variable debug information.
  3811. if (CGDebugInfo *DI = getModuleDebugInfo())
  3812. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3813. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  3814. OMD->getClassInterface()), OMD->getLocation());
  3815. break;
  3816. }
  3817. case Decl::ObjCMethod: {
  3818. auto *OMD = cast<ObjCMethodDecl>(D);
  3819. // If this is not a prototype, emit the body.
  3820. if (OMD->getBody())
  3821. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  3822. break;
  3823. }
  3824. case Decl::ObjCCompatibleAlias:
  3825. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  3826. break;
  3827. case Decl::PragmaComment: {
  3828. const auto *PCD = cast<PragmaCommentDecl>(D);
  3829. switch (PCD->getCommentKind()) {
  3830. case PCK_Unknown:
  3831. llvm_unreachable("unexpected pragma comment kind");
  3832. case PCK_Linker:
  3833. AppendLinkerOptions(PCD->getArg());
  3834. break;
  3835. case PCK_Lib:
  3836. if (getTarget().getTriple().isOSBinFormatELF() &&
  3837. !getTarget().getTriple().isPS4())
  3838. AddELFLibDirective(PCD->getArg());
  3839. else
  3840. AddDependentLib(PCD->getArg());
  3841. break;
  3842. case PCK_Compiler:
  3843. case PCK_ExeStr:
  3844. case PCK_User:
  3845. break; // We ignore all of these.
  3846. }
  3847. break;
  3848. }
  3849. case Decl::PragmaDetectMismatch: {
  3850. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  3851. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  3852. break;
  3853. }
  3854. case Decl::LinkageSpec:
  3855. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  3856. break;
  3857. case Decl::FileScopeAsm: {
  3858. // File-scope asm is ignored during device-side CUDA compilation.
  3859. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  3860. break;
  3861. // File-scope asm is ignored during device-side OpenMP compilation.
  3862. if (LangOpts.OpenMPIsDevice)
  3863. break;
  3864. auto *AD = cast<FileScopeAsmDecl>(D);
  3865. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  3866. break;
  3867. }
  3868. case Decl::Import: {
  3869. auto *Import = cast<ImportDecl>(D);
  3870. // If we've already imported this module, we're done.
  3871. if (!ImportedModules.insert(Import->getImportedModule()))
  3872. break;
  3873. // Emit debug information for direct imports.
  3874. if (!Import->getImportedOwningModule()) {
  3875. if (CGDebugInfo *DI = getModuleDebugInfo())
  3876. DI->EmitImportDecl(*Import);
  3877. }
  3878. // Find all of the submodules and emit the module initializers.
  3879. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  3880. SmallVector<clang::Module *, 16> Stack;
  3881. Visited.insert(Import->getImportedModule());
  3882. Stack.push_back(Import->getImportedModule());
  3883. while (!Stack.empty()) {
  3884. clang::Module *Mod = Stack.pop_back_val();
  3885. if (!EmittedModuleInitializers.insert(Mod).second)
  3886. continue;
  3887. for (auto *D : Context.getModuleInitializers(Mod))
  3888. EmitTopLevelDecl(D);
  3889. // Visit the submodules of this module.
  3890. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  3891. SubEnd = Mod->submodule_end();
  3892. Sub != SubEnd; ++Sub) {
  3893. // Skip explicit children; they need to be explicitly imported to emit
  3894. // the initializers.
  3895. if ((*Sub)->IsExplicit)
  3896. continue;
  3897. if (Visited.insert(*Sub).second)
  3898. Stack.push_back(*Sub);
  3899. }
  3900. }
  3901. break;
  3902. }
  3903. case Decl::Export:
  3904. EmitDeclContext(cast<ExportDecl>(D));
  3905. break;
  3906. case Decl::OMPThreadPrivate:
  3907. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  3908. break;
  3909. case Decl::OMPDeclareReduction:
  3910. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  3911. break;
  3912. default:
  3913. // Make sure we handled everything we should, every other kind is a
  3914. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  3915. // function. Need to recode Decl::Kind to do that easily.
  3916. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  3917. break;
  3918. }
  3919. }
  3920. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  3921. // Do we need to generate coverage mapping?
  3922. if (!CodeGenOpts.CoverageMapping)
  3923. return;
  3924. switch (D->getKind()) {
  3925. case Decl::CXXConversion:
  3926. case Decl::CXXMethod:
  3927. case Decl::Function:
  3928. case Decl::ObjCMethod:
  3929. case Decl::CXXConstructor:
  3930. case Decl::CXXDestructor: {
  3931. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  3932. return;
  3933. SourceManager &SM = getContext().getSourceManager();
  3934. if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
  3935. return;
  3936. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3937. if (I == DeferredEmptyCoverageMappingDecls.end())
  3938. DeferredEmptyCoverageMappingDecls[D] = true;
  3939. break;
  3940. }
  3941. default:
  3942. break;
  3943. };
  3944. }
  3945. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  3946. // Do we need to generate coverage mapping?
  3947. if (!CodeGenOpts.CoverageMapping)
  3948. return;
  3949. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  3950. if (Fn->isTemplateInstantiation())
  3951. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  3952. }
  3953. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3954. if (I == DeferredEmptyCoverageMappingDecls.end())
  3955. DeferredEmptyCoverageMappingDecls[D] = false;
  3956. else
  3957. I->second = false;
  3958. }
  3959. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  3960. // We call takeVector() here to avoid use-after-free.
  3961. // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
  3962. // we deserialize function bodies to emit coverage info for them, and that
  3963. // deserializes more declarations. How should we handle that case?
  3964. for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
  3965. if (!Entry.second)
  3966. continue;
  3967. const Decl *D = Entry.first;
  3968. switch (D->getKind()) {
  3969. case Decl::CXXConversion:
  3970. case Decl::CXXMethod:
  3971. case Decl::Function:
  3972. case Decl::ObjCMethod: {
  3973. CodeGenPGO PGO(*this);
  3974. GlobalDecl GD(cast<FunctionDecl>(D));
  3975. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3976. getFunctionLinkage(GD));
  3977. break;
  3978. }
  3979. case Decl::CXXConstructor: {
  3980. CodeGenPGO PGO(*this);
  3981. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  3982. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3983. getFunctionLinkage(GD));
  3984. break;
  3985. }
  3986. case Decl::CXXDestructor: {
  3987. CodeGenPGO PGO(*this);
  3988. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  3989. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3990. getFunctionLinkage(GD));
  3991. break;
  3992. }
  3993. default:
  3994. break;
  3995. };
  3996. }
  3997. }
  3998. /// Turns the given pointer into a constant.
  3999. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  4000. const void *Ptr) {
  4001. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  4002. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  4003. return llvm::ConstantInt::get(i64, PtrInt);
  4004. }
  4005. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  4006. llvm::NamedMDNode *&GlobalMetadata,
  4007. GlobalDecl D,
  4008. llvm::GlobalValue *Addr) {
  4009. if (!GlobalMetadata)
  4010. GlobalMetadata =
  4011. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  4012. // TODO: should we report variant information for ctors/dtors?
  4013. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  4014. llvm::ConstantAsMetadata::get(GetPointerConstant(
  4015. CGM.getLLVMContext(), D.getDecl()))};
  4016. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  4017. }
  4018. /// For each function which is declared within an extern "C" region and marked
  4019. /// as 'used', but has internal linkage, create an alias from the unmangled
  4020. /// name to the mangled name if possible. People expect to be able to refer
  4021. /// to such functions with an unmangled name from inline assembly within the
  4022. /// same translation unit.
  4023. void CodeGenModule::EmitStaticExternCAliases() {
  4024. // Don't do anything if we're generating CUDA device code -- the NVPTX
  4025. // assembly target doesn't support aliases.
  4026. if (Context.getTargetInfo().getTriple().isNVPTX())
  4027. return;
  4028. for (auto &I : StaticExternCValues) {
  4029. IdentifierInfo *Name = I.first;
  4030. llvm::GlobalValue *Val = I.second;
  4031. if (Val && !getModule().getNamedValue(Name->getName()))
  4032. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  4033. }
  4034. }
  4035. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  4036. GlobalDecl &Result) const {
  4037. auto Res = Manglings.find(MangledName);
  4038. if (Res == Manglings.end())
  4039. return false;
  4040. Result = Res->getValue();
  4041. return true;
  4042. }
  4043. /// Emits metadata nodes associating all the global values in the
  4044. /// current module with the Decls they came from. This is useful for
  4045. /// projects using IR gen as a subroutine.
  4046. ///
  4047. /// Since there's currently no way to associate an MDNode directly
  4048. /// with an llvm::GlobalValue, we create a global named metadata
  4049. /// with the name 'clang.global.decl.ptrs'.
  4050. void CodeGenModule::EmitDeclMetadata() {
  4051. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4052. for (auto &I : MangledDeclNames) {
  4053. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  4054. // Some mangled names don't necessarily have an associated GlobalValue
  4055. // in this module, e.g. if we mangled it for DebugInfo.
  4056. if (Addr)
  4057. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  4058. }
  4059. }
  4060. /// Emits metadata nodes for all the local variables in the current
  4061. /// function.
  4062. void CodeGenFunction::EmitDeclMetadata() {
  4063. if (LocalDeclMap.empty()) return;
  4064. llvm::LLVMContext &Context = getLLVMContext();
  4065. // Find the unique metadata ID for this name.
  4066. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  4067. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4068. for (auto &I : LocalDeclMap) {
  4069. const Decl *D = I.first;
  4070. llvm::Value *Addr = I.second.getPointer();
  4071. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  4072. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  4073. Alloca->setMetadata(
  4074. DeclPtrKind, llvm::MDNode::get(
  4075. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  4076. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  4077. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  4078. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  4079. }
  4080. }
  4081. }
  4082. void CodeGenModule::EmitVersionIdentMetadata() {
  4083. llvm::NamedMDNode *IdentMetadata =
  4084. TheModule.getOrInsertNamedMetadata("llvm.ident");
  4085. std::string Version = getClangFullVersion();
  4086. llvm::LLVMContext &Ctx = TheModule.getContext();
  4087. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  4088. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  4089. }
  4090. void CodeGenModule::EmitTargetMetadata() {
  4091. // Warning, new MangledDeclNames may be appended within this loop.
  4092. // We rely on MapVector insertions adding new elements to the end
  4093. // of the container.
  4094. // FIXME: Move this loop into the one target that needs it, and only
  4095. // loop over those declarations for which we couldn't emit the target
  4096. // metadata when we emitted the declaration.
  4097. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  4098. auto Val = *(MangledDeclNames.begin() + I);
  4099. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  4100. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  4101. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  4102. }
  4103. }
  4104. void CodeGenModule::EmitCoverageFile() {
  4105. if (getCodeGenOpts().CoverageDataFile.empty() &&
  4106. getCodeGenOpts().CoverageNotesFile.empty())
  4107. return;
  4108. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  4109. if (!CUNode)
  4110. return;
  4111. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  4112. llvm::LLVMContext &Ctx = TheModule.getContext();
  4113. auto *CoverageDataFile =
  4114. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  4115. auto *CoverageNotesFile =
  4116. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  4117. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  4118. llvm::MDNode *CU = CUNode->getOperand(i);
  4119. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  4120. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  4121. }
  4122. }
  4123. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  4124. // Sema has checked that all uuid strings are of the form
  4125. // "12345678-1234-1234-1234-1234567890ab".
  4126. assert(Uuid.size() == 36);
  4127. for (unsigned i = 0; i < 36; ++i) {
  4128. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  4129. else assert(isHexDigit(Uuid[i]));
  4130. }
  4131. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  4132. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  4133. llvm::Constant *Field3[8];
  4134. for (unsigned Idx = 0; Idx < 8; ++Idx)
  4135. Field3[Idx] = llvm::ConstantInt::get(
  4136. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  4137. llvm::Constant *Fields[4] = {
  4138. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  4139. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  4140. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  4141. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  4142. };
  4143. return llvm::ConstantStruct::getAnon(Fields);
  4144. }
  4145. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  4146. bool ForEH) {
  4147. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  4148. // FIXME: should we even be calling this method if RTTI is disabled
  4149. // and it's not for EH?
  4150. if (!ForEH && !getLangOpts().RTTI)
  4151. return llvm::Constant::getNullValue(Int8PtrTy);
  4152. if (ForEH && Ty->isObjCObjectPointerType() &&
  4153. LangOpts.ObjCRuntime.isGNUFamily())
  4154. return ObjCRuntime->GetEHType(Ty);
  4155. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  4156. }
  4157. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  4158. // Do not emit threadprivates in simd-only mode.
  4159. if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
  4160. return;
  4161. for (auto RefExpr : D->varlists()) {
  4162. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  4163. bool PerformInit =
  4164. VD->getAnyInitializer() &&
  4165. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  4166. /*ForRef=*/false);
  4167. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  4168. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  4169. VD, Addr, RefExpr->getLocStart(), PerformInit))
  4170. CXXGlobalInits.push_back(InitFunction);
  4171. }
  4172. }
  4173. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  4174. llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
  4175. if (InternalId)
  4176. return InternalId;
  4177. if (isExternallyVisible(T->getLinkage())) {
  4178. std::string OutName;
  4179. llvm::raw_string_ostream Out(OutName);
  4180. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  4181. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  4182. } else {
  4183. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  4184. llvm::ArrayRef<llvm::Metadata *>());
  4185. }
  4186. return InternalId;
  4187. }
  4188. // Generalize pointer types to a void pointer with the qualifiers of the
  4189. // originally pointed-to type, e.g. 'const char *' and 'char * const *'
  4190. // generalize to 'const void *' while 'char *' and 'const char **' generalize to
  4191. // 'void *'.
  4192. static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
  4193. if (!Ty->isPointerType())
  4194. return Ty;
  4195. return Ctx.getPointerType(
  4196. QualType(Ctx.VoidTy).withCVRQualifiers(
  4197. Ty->getPointeeType().getCVRQualifiers()));
  4198. }
  4199. // Apply type generalization to a FunctionType's return and argument types
  4200. static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
  4201. if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
  4202. SmallVector<QualType, 8> GeneralizedParams;
  4203. for (auto &Param : FnType->param_types())
  4204. GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
  4205. return Ctx.getFunctionType(
  4206. GeneralizeType(Ctx, FnType->getReturnType()),
  4207. GeneralizedParams, FnType->getExtProtoInfo());
  4208. }
  4209. if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
  4210. return Ctx.getFunctionNoProtoType(
  4211. GeneralizeType(Ctx, FnType->getReturnType()));
  4212. llvm_unreachable("Encountered unknown FunctionType");
  4213. }
  4214. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
  4215. T = GeneralizeFunctionType(getContext(), T);
  4216. llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()];
  4217. if (InternalId)
  4218. return InternalId;
  4219. if (isExternallyVisible(T->getLinkage())) {
  4220. std::string OutName;
  4221. llvm::raw_string_ostream Out(OutName);
  4222. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  4223. Out << ".generalized";
  4224. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  4225. } else {
  4226. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  4227. llvm::ArrayRef<llvm::Metadata *>());
  4228. }
  4229. return InternalId;
  4230. }
  4231. /// Returns whether this module needs the "all-vtables" type identifier.
  4232. bool CodeGenModule::NeedAllVtablesTypeId() const {
  4233. // Returns true if at least one of vtable-based CFI checkers is enabled and
  4234. // is not in the trapping mode.
  4235. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  4236. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  4237. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  4238. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  4239. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  4240. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  4241. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  4242. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  4243. }
  4244. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  4245. CharUnits Offset,
  4246. const CXXRecordDecl *RD) {
  4247. llvm::Metadata *MD =
  4248. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  4249. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4250. if (CodeGenOpts.SanitizeCfiCrossDso)
  4251. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  4252. VTable->addTypeMetadata(Offset.getQuantity(),
  4253. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  4254. if (NeedAllVtablesTypeId()) {
  4255. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  4256. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4257. }
  4258. }
  4259. // Fills in the supplied string map with the set of target features for the
  4260. // passed in function.
  4261. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  4262. const FunctionDecl *FD) {
  4263. StringRef TargetCPU = Target.getTargetOpts().CPU;
  4264. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  4265. // If we have a TargetAttr build up the feature map based on that.
  4266. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  4267. ParsedAttr.Features.erase(
  4268. llvm::remove_if(ParsedAttr.Features,
  4269. [&](const std::string &Feat) {
  4270. return !Target.isValidFeatureName(
  4271. StringRef{Feat}.substr(1));
  4272. }),
  4273. ParsedAttr.Features.end());
  4274. // Make a copy of the features as passed on the command line into the
  4275. // beginning of the additional features from the function to override.
  4276. ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
  4277. Target.getTargetOpts().FeaturesAsWritten.begin(),
  4278. Target.getTargetOpts().FeaturesAsWritten.end());
  4279. if (ParsedAttr.Architecture != "" &&
  4280. Target.isValidCPUName(ParsedAttr.Architecture))
  4281. TargetCPU = ParsedAttr.Architecture;
  4282. // Now populate the feature map, first with the TargetCPU which is either
  4283. // the default or a new one from the target attribute string. Then we'll use
  4284. // the passed in features (FeaturesAsWritten) along with the new ones from
  4285. // the attribute.
  4286. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4287. ParsedAttr.Features);
  4288. } else {
  4289. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4290. Target.getTargetOpts().Features);
  4291. }
  4292. }
  4293. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  4294. if (!SanStats)
  4295. SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
  4296. return *SanStats;
  4297. }
  4298. llvm::Value *
  4299. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  4300. CodeGenFunction &CGF) {
  4301. llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
  4302. auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
  4303. auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  4304. return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
  4305. "__translate_sampler_initializer"),
  4306. {C});
  4307. }