CodeGenModule.cpp 223 KB

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