CBackend.cpp 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620
  1. //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This library converts LLVM code to C code, compilable by GCC and other C
  11. // compilers.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CTargetMachine.h"
  15. #include "llvm/CallingConv.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/Module.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/Pass.h"
  21. #include "llvm/PassManager.h"
  22. #include "llvm/TypeSymbolTable.h"
  23. #include "llvm/Intrinsics.h"
  24. #include "llvm/IntrinsicInst.h"
  25. #include "llvm/InlineAsm.h"
  26. #include "llvm/Analysis/ConstantsScanner.h"
  27. #include "llvm/Analysis/FindUsedTypes.h"
  28. #include "llvm/Analysis/LoopInfo.h"
  29. #include "llvm/CodeGen/Passes.h"
  30. #include "llvm/CodeGen/IntrinsicLowering.h"
  31. #include "llvm/Transforms/Scalar.h"
  32. #include "llvm/Target/TargetMachineRegistry.h"
  33. #include "llvm/Target/TargetAsmInfo.h"
  34. #include "llvm/Target/TargetData.h"
  35. #include "llvm/Support/CallSite.h"
  36. #include "llvm/Support/CFG.h"
  37. #include "llvm/Support/GetElementPtrTypeIterator.h"
  38. #include "llvm/Support/InstVisitor.h"
  39. #include "llvm/Support/Mangler.h"
  40. #include "llvm/Support/MathExtras.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include "llvm/ADT/StringExtras.h"
  43. #include "llvm/ADT/STLExtras.h"
  44. #include "llvm/Support/MathExtras.h"
  45. #include "llvm/Config/config.h"
  46. #include <algorithm>
  47. #include <sstream>
  48. using namespace llvm;
  49. /// CBackendTargetMachineModule - Note that this is used on hosts that
  50. /// cannot link in a library unless there are references into the
  51. /// library. In particular, it seems that it is not possible to get
  52. /// things to work on Win32 without this. Though it is unused, do not
  53. /// remove it.
  54. extern "C" int CBackendTargetMachineModule;
  55. int CBackendTargetMachineModule = 0;
  56. // Register the target.
  57. static RegisterTarget<CTargetMachine> X("c", "C backend");
  58. // Force static initialization.
  59. extern "C" void LLVMInitializeCBackendTarget() { }
  60. namespace {
  61. /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
  62. /// any unnamed structure types that are used by the program, and merges
  63. /// external functions with the same name.
  64. ///
  65. class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
  66. public:
  67. static char ID;
  68. CBackendNameAllUsedStructsAndMergeFunctions()
  69. : ModulePass(&ID) {}
  70. void getAnalysisUsage(AnalysisUsage &AU) const {
  71. AU.addRequired<FindUsedTypes>();
  72. }
  73. virtual const char *getPassName() const {
  74. return "C backend type canonicalizer";
  75. }
  76. virtual bool runOnModule(Module &M);
  77. };
  78. char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
  79. /// CWriter - This class is the main chunk of code that converts an LLVM
  80. /// module to a C translation unit.
  81. class CWriter : public FunctionPass, public InstVisitor<CWriter> {
  82. raw_ostream &Out;
  83. IntrinsicLowering *IL;
  84. Mangler *Mang;
  85. LoopInfo *LI;
  86. const Module *TheModule;
  87. const TargetAsmInfo* TAsm;
  88. const TargetData* TD;
  89. std::map<const Type *, std::string> TypeNames;
  90. std::map<const ConstantFP *, unsigned> FPConstantMap;
  91. std::set<Function*> intrinsicPrototypesAlreadyGenerated;
  92. std::set<const Argument*> ByValParams;
  93. unsigned FPCounter;
  94. public:
  95. static char ID;
  96. explicit CWriter(raw_ostream &o)
  97. : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
  98. TheModule(0), TAsm(0), TD(0) {
  99. FPCounter = 0;
  100. }
  101. virtual const char *getPassName() const { return "C backend"; }
  102. void getAnalysisUsage(AnalysisUsage &AU) const {
  103. AU.addRequired<LoopInfo>();
  104. AU.setPreservesAll();
  105. }
  106. virtual bool doInitialization(Module &M);
  107. bool runOnFunction(Function &F) {
  108. // Do not codegen any 'available_externally' functions at all, they have
  109. // definitions outside the translation unit.
  110. if (F.hasAvailableExternallyLinkage())
  111. return false;
  112. LI = &getAnalysis<LoopInfo>();
  113. // Get rid of intrinsics we can't handle.
  114. lowerIntrinsics(F);
  115. // Output all floating point constants that cannot be printed accurately.
  116. printFloatingPointConstants(F);
  117. printFunction(F);
  118. return false;
  119. }
  120. virtual bool doFinalization(Module &M) {
  121. // Free memory...
  122. delete IL;
  123. delete TD;
  124. delete Mang;
  125. FPConstantMap.clear();
  126. TypeNames.clear();
  127. ByValParams.clear();
  128. intrinsicPrototypesAlreadyGenerated.clear();
  129. return false;
  130. }
  131. raw_ostream &printType(raw_ostream &Out, const Type *Ty,
  132. bool isSigned = false,
  133. const std::string &VariableName = "",
  134. bool IgnoreName = false,
  135. const AttrListPtr &PAL = AttrListPtr());
  136. std::ostream &printType(std::ostream &Out, const Type *Ty,
  137. bool isSigned = false,
  138. const std::string &VariableName = "",
  139. bool IgnoreName = false,
  140. const AttrListPtr &PAL = AttrListPtr());
  141. raw_ostream &printSimpleType(raw_ostream &Out, const Type *Ty,
  142. bool isSigned,
  143. const std::string &NameSoFar = "");
  144. std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
  145. bool isSigned,
  146. const std::string &NameSoFar = "");
  147. void printStructReturnPointerFunctionType(raw_ostream &Out,
  148. const AttrListPtr &PAL,
  149. const PointerType *Ty);
  150. /// writeOperandDeref - Print the result of dereferencing the specified
  151. /// operand with '*'. This is equivalent to printing '*' then using
  152. /// writeOperand, but avoids excess syntax in some cases.
  153. void writeOperandDeref(Value *Operand) {
  154. if (isAddressExposed(Operand)) {
  155. // Already something with an address exposed.
  156. writeOperandInternal(Operand);
  157. } else {
  158. Out << "*(";
  159. writeOperand(Operand);
  160. Out << ")";
  161. }
  162. }
  163. void writeOperand(Value *Operand, bool Static = false);
  164. void writeInstComputationInline(Instruction &I);
  165. void writeOperandInternal(Value *Operand, bool Static = false);
  166. void writeOperandWithCast(Value* Operand, unsigned Opcode);
  167. void writeOperandWithCast(Value* Operand, const ICmpInst &I);
  168. bool writeInstructionCast(const Instruction &I);
  169. void writeMemoryAccess(Value *Operand, const Type *OperandType,
  170. bool IsVolatile, unsigned Alignment);
  171. private :
  172. std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
  173. void lowerIntrinsics(Function &F);
  174. void printModule(Module *M);
  175. void printModuleTypes(const TypeSymbolTable &ST);
  176. void printContainedStructs(const Type *Ty, std::set<const Type *> &);
  177. void printFloatingPointConstants(Function &F);
  178. void printFloatingPointConstants(const Constant *C);
  179. void printFunctionSignature(const Function *F, bool Prototype);
  180. void printFunction(Function &);
  181. void printBasicBlock(BasicBlock *BB);
  182. void printLoop(Loop *L);
  183. void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
  184. void printConstant(Constant *CPV, bool Static);
  185. void printConstantWithCast(Constant *CPV, unsigned Opcode);
  186. bool printConstExprCast(const ConstantExpr *CE, bool Static);
  187. void printConstantArray(ConstantArray *CPA, bool Static);
  188. void printConstantVector(ConstantVector *CV, bool Static);
  189. /// isAddressExposed - Return true if the specified value's name needs to
  190. /// have its address taken in order to get a C value of the correct type.
  191. /// This happens for global variables, byval parameters, and direct allocas.
  192. bool isAddressExposed(const Value *V) const {
  193. if (const Argument *A = dyn_cast<Argument>(V))
  194. return ByValParams.count(A);
  195. return isa<GlobalVariable>(V) || isDirectAlloca(V);
  196. }
  197. // isInlinableInst - Attempt to inline instructions into their uses to build
  198. // trees as much as possible. To do this, we have to consistently decide
  199. // what is acceptable to inline, so that variable declarations don't get
  200. // printed and an extra copy of the expr is not emitted.
  201. //
  202. static bool isInlinableInst(const Instruction &I) {
  203. // Always inline cmp instructions, even if they are shared by multiple
  204. // expressions. GCC generates horrible code if we don't.
  205. if (isa<CmpInst>(I))
  206. return true;
  207. // Must be an expression, must be used exactly once. If it is dead, we
  208. // emit it inline where it would go.
  209. if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
  210. isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
  211. isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
  212. isa<InsertValueInst>(I))
  213. // Don't inline a load across a store or other bad things!
  214. return false;
  215. // Must not be used in inline asm, extractelement, or shufflevector.
  216. if (I.hasOneUse()) {
  217. const Instruction &User = cast<Instruction>(*I.use_back());
  218. if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
  219. isa<ShuffleVectorInst>(User))
  220. return false;
  221. }
  222. // Only inline instruction it if it's use is in the same BB as the inst.
  223. return I.getParent() == cast<Instruction>(I.use_back())->getParent();
  224. }
  225. // isDirectAlloca - Define fixed sized allocas in the entry block as direct
  226. // variables which are accessed with the & operator. This causes GCC to
  227. // generate significantly better code than to emit alloca calls directly.
  228. //
  229. static const AllocaInst *isDirectAlloca(const Value *V) {
  230. const AllocaInst *AI = dyn_cast<AllocaInst>(V);
  231. if (!AI) return false;
  232. if (AI->isArrayAllocation())
  233. return 0; // FIXME: we can also inline fixed size array allocas!
  234. if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
  235. return 0;
  236. return AI;
  237. }
  238. // isInlineAsm - Check if the instruction is a call to an inline asm chunk
  239. static bool isInlineAsm(const Instruction& I) {
  240. if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
  241. return true;
  242. return false;
  243. }
  244. // Instruction visitation functions
  245. friend class InstVisitor<CWriter>;
  246. void visitReturnInst(ReturnInst &I);
  247. void visitBranchInst(BranchInst &I);
  248. void visitSwitchInst(SwitchInst &I);
  249. void visitInvokeInst(InvokeInst &I) {
  250. assert(0 && "Lowerinvoke pass didn't work!");
  251. }
  252. void visitUnwindInst(UnwindInst &I) {
  253. assert(0 && "Lowerinvoke pass didn't work!");
  254. }
  255. void visitUnreachableInst(UnreachableInst &I);
  256. void visitPHINode(PHINode &I);
  257. void visitBinaryOperator(Instruction &I);
  258. void visitICmpInst(ICmpInst &I);
  259. void visitFCmpInst(FCmpInst &I);
  260. void visitCastInst (CastInst &I);
  261. void visitSelectInst(SelectInst &I);
  262. void visitCallInst (CallInst &I);
  263. void visitInlineAsm(CallInst &I);
  264. bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
  265. void visitMallocInst(MallocInst &I);
  266. void visitAllocaInst(AllocaInst &I);
  267. void visitFreeInst (FreeInst &I);
  268. void visitLoadInst (LoadInst &I);
  269. void visitStoreInst (StoreInst &I);
  270. void visitGetElementPtrInst(GetElementPtrInst &I);
  271. void visitVAArgInst (VAArgInst &I);
  272. void visitInsertElementInst(InsertElementInst &I);
  273. void visitExtractElementInst(ExtractElementInst &I);
  274. void visitShuffleVectorInst(ShuffleVectorInst &SVI);
  275. void visitInsertValueInst(InsertValueInst &I);
  276. void visitExtractValueInst(ExtractValueInst &I);
  277. void visitInstruction(Instruction &I) {
  278. cerr << "C Writer does not know about " << I;
  279. abort();
  280. }
  281. void outputLValue(Instruction *I) {
  282. Out << " " << GetValueName(I) << " = ";
  283. }
  284. bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
  285. void printPHICopiesForSuccessor(BasicBlock *CurBlock,
  286. BasicBlock *Successor, unsigned Indent);
  287. void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
  288. unsigned Indent);
  289. void printGEPExpression(Value *Ptr, gep_type_iterator I,
  290. gep_type_iterator E, bool Static);
  291. std::string GetValueName(const Value *Operand);
  292. };
  293. }
  294. char CWriter::ID = 0;
  295. /// This method inserts names for any unnamed structure types that are used by
  296. /// the program, and removes names from structure types that are not used by the
  297. /// program.
  298. ///
  299. bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
  300. // Get a set of types that are used by the program...
  301. std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
  302. // Loop over the module symbol table, removing types from UT that are
  303. // already named, and removing names for types that are not used.
  304. //
  305. TypeSymbolTable &TST = M.getTypeSymbolTable();
  306. for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
  307. TI != TE; ) {
  308. TypeSymbolTable::iterator I = TI++;
  309. // If this isn't a struct or array type, remove it from our set of types
  310. // to name. This simplifies emission later.
  311. if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
  312. !isa<ArrayType>(I->second)) {
  313. TST.remove(I);
  314. } else {
  315. // If this is not used, remove it from the symbol table.
  316. std::set<const Type *>::iterator UTI = UT.find(I->second);
  317. if (UTI == UT.end())
  318. TST.remove(I);
  319. else
  320. UT.erase(UTI); // Only keep one name for this type.
  321. }
  322. }
  323. // UT now contains types that are not named. Loop over it, naming
  324. // structure types.
  325. //
  326. bool Changed = false;
  327. unsigned RenameCounter = 0;
  328. for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
  329. I != E; ++I)
  330. if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
  331. while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
  332. ++RenameCounter;
  333. Changed = true;
  334. }
  335. // Loop over all external functions and globals. If we have two with
  336. // identical names, merge them.
  337. // FIXME: This code should disappear when we don't allow values with the same
  338. // names when they have different types!
  339. std::map<std::string, GlobalValue*> ExtSymbols;
  340. for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
  341. Function *GV = I++;
  342. if (GV->isDeclaration() && GV->hasName()) {
  343. std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
  344. = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
  345. if (!X.second) {
  346. // Found a conflict, replace this global with the previous one.
  347. GlobalValue *OldGV = X.first->second;
  348. GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
  349. GV->eraseFromParent();
  350. Changed = true;
  351. }
  352. }
  353. }
  354. // Do the same for globals.
  355. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  356. I != E;) {
  357. GlobalVariable *GV = I++;
  358. if (GV->isDeclaration() && GV->hasName()) {
  359. std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
  360. = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
  361. if (!X.second) {
  362. // Found a conflict, replace this global with the previous one.
  363. GlobalValue *OldGV = X.first->second;
  364. GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
  365. GV->eraseFromParent();
  366. Changed = true;
  367. }
  368. }
  369. }
  370. return Changed;
  371. }
  372. /// printStructReturnPointerFunctionType - This is like printType for a struct
  373. /// return type, except, instead of printing the type as void (*)(Struct*, ...)
  374. /// print it as "Struct (*)(...)", for struct return functions.
  375. void CWriter::printStructReturnPointerFunctionType(raw_ostream &Out,
  376. const AttrListPtr &PAL,
  377. const PointerType *TheTy) {
  378. const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
  379. std::stringstream FunctionInnards;
  380. FunctionInnards << " (*) (";
  381. bool PrintedType = false;
  382. FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
  383. const Type *RetTy = cast<PointerType>(I->get())->getElementType();
  384. unsigned Idx = 1;
  385. for (++I, ++Idx; I != E; ++I, ++Idx) {
  386. if (PrintedType)
  387. FunctionInnards << ", ";
  388. const Type *ArgTy = *I;
  389. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  390. assert(isa<PointerType>(ArgTy));
  391. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  392. }
  393. printType(FunctionInnards, ArgTy,
  394. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
  395. PrintedType = true;
  396. }
  397. if (FTy->isVarArg()) {
  398. if (PrintedType)
  399. FunctionInnards << ", ...";
  400. } else if (!PrintedType) {
  401. FunctionInnards << "void";
  402. }
  403. FunctionInnards << ')';
  404. std::string tstr = FunctionInnards.str();
  405. printType(Out, RetTy,
  406. /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
  407. }
  408. raw_ostream &
  409. CWriter::printSimpleType(raw_ostream &Out, const Type *Ty, bool isSigned,
  410. const std::string &NameSoFar) {
  411. assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
  412. "Invalid type for printSimpleType");
  413. switch (Ty->getTypeID()) {
  414. case Type::VoidTyID: return Out << "void " << NameSoFar;
  415. case Type::IntegerTyID: {
  416. unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
  417. if (NumBits == 1)
  418. return Out << "bool " << NameSoFar;
  419. else if (NumBits <= 8)
  420. return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
  421. else if (NumBits <= 16)
  422. return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
  423. else if (NumBits <= 32)
  424. return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
  425. else if (NumBits <= 64)
  426. return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
  427. else {
  428. assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
  429. return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
  430. }
  431. }
  432. case Type::FloatTyID: return Out << "float " << NameSoFar;
  433. case Type::DoubleTyID: return Out << "double " << NameSoFar;
  434. // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
  435. // present matches host 'long double'.
  436. case Type::X86_FP80TyID:
  437. case Type::PPC_FP128TyID:
  438. case Type::FP128TyID: return Out << "long double " << NameSoFar;
  439. case Type::VectorTyID: {
  440. const VectorType *VTy = cast<VectorType>(Ty);
  441. return printSimpleType(Out, VTy->getElementType(), isSigned,
  442. " __attribute__((vector_size(" +
  443. utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
  444. }
  445. default:
  446. cerr << "Unknown primitive type: " << *Ty << "\n";
  447. abort();
  448. }
  449. }
  450. std::ostream &
  451. CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
  452. const std::string &NameSoFar) {
  453. assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
  454. "Invalid type for printSimpleType");
  455. switch (Ty->getTypeID()) {
  456. case Type::VoidTyID: return Out << "void " << NameSoFar;
  457. case Type::IntegerTyID: {
  458. unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
  459. if (NumBits == 1)
  460. return Out << "bool " << NameSoFar;
  461. else if (NumBits <= 8)
  462. return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
  463. else if (NumBits <= 16)
  464. return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
  465. else if (NumBits <= 32)
  466. return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
  467. else if (NumBits <= 64)
  468. return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
  469. else {
  470. assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
  471. return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
  472. }
  473. }
  474. case Type::FloatTyID: return Out << "float " << NameSoFar;
  475. case Type::DoubleTyID: return Out << "double " << NameSoFar;
  476. // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
  477. // present matches host 'long double'.
  478. case Type::X86_FP80TyID:
  479. case Type::PPC_FP128TyID:
  480. case Type::FP128TyID: return Out << "long double " << NameSoFar;
  481. case Type::VectorTyID: {
  482. const VectorType *VTy = cast<VectorType>(Ty);
  483. return printSimpleType(Out, VTy->getElementType(), isSigned,
  484. " __attribute__((vector_size(" +
  485. utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
  486. }
  487. default:
  488. cerr << "Unknown primitive type: " << *Ty << "\n";
  489. abort();
  490. }
  491. }
  492. // Pass the Type* and the variable name and this prints out the variable
  493. // declaration.
  494. //
  495. raw_ostream &CWriter::printType(raw_ostream &Out, const Type *Ty,
  496. bool isSigned, const std::string &NameSoFar,
  497. bool IgnoreName, const AttrListPtr &PAL) {
  498. if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
  499. printSimpleType(Out, Ty, isSigned, NameSoFar);
  500. return Out;
  501. }
  502. // Check to see if the type is named.
  503. if (!IgnoreName || isa<OpaqueType>(Ty)) {
  504. std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
  505. if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
  506. }
  507. switch (Ty->getTypeID()) {
  508. case Type::FunctionTyID: {
  509. const FunctionType *FTy = cast<FunctionType>(Ty);
  510. std::stringstream FunctionInnards;
  511. FunctionInnards << " (" << NameSoFar << ") (";
  512. unsigned Idx = 1;
  513. for (FunctionType::param_iterator I = FTy->param_begin(),
  514. E = FTy->param_end(); I != E; ++I) {
  515. const Type *ArgTy = *I;
  516. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  517. assert(isa<PointerType>(ArgTy));
  518. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  519. }
  520. if (I != FTy->param_begin())
  521. FunctionInnards << ", ";
  522. printType(FunctionInnards, ArgTy,
  523. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
  524. ++Idx;
  525. }
  526. if (FTy->isVarArg()) {
  527. if (FTy->getNumParams())
  528. FunctionInnards << ", ...";
  529. } else if (!FTy->getNumParams()) {
  530. FunctionInnards << "void";
  531. }
  532. FunctionInnards << ')';
  533. std::string tstr = FunctionInnards.str();
  534. printType(Out, FTy->getReturnType(),
  535. /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
  536. return Out;
  537. }
  538. case Type::StructTyID: {
  539. const StructType *STy = cast<StructType>(Ty);
  540. Out << NameSoFar + " {\n";
  541. unsigned Idx = 0;
  542. for (StructType::element_iterator I = STy->element_begin(),
  543. E = STy->element_end(); I != E; ++I) {
  544. Out << " ";
  545. printType(Out, *I, false, "field" + utostr(Idx++));
  546. Out << ";\n";
  547. }
  548. Out << '}';
  549. if (STy->isPacked())
  550. Out << " __attribute__ ((packed))";
  551. return Out;
  552. }
  553. case Type::PointerTyID: {
  554. const PointerType *PTy = cast<PointerType>(Ty);
  555. std::string ptrName = "*" + NameSoFar;
  556. if (isa<ArrayType>(PTy->getElementType()) ||
  557. isa<VectorType>(PTy->getElementType()))
  558. ptrName = "(" + ptrName + ")";
  559. if (!PAL.isEmpty())
  560. // Must be a function ptr cast!
  561. return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
  562. return printType(Out, PTy->getElementType(), false, ptrName);
  563. }
  564. case Type::ArrayTyID: {
  565. const ArrayType *ATy = cast<ArrayType>(Ty);
  566. unsigned NumElements = ATy->getNumElements();
  567. if (NumElements == 0) NumElements = 1;
  568. // Arrays are wrapped in structs to allow them to have normal
  569. // value semantics (avoiding the array "decay").
  570. Out << NameSoFar << " { ";
  571. printType(Out, ATy->getElementType(), false,
  572. "array[" + utostr(NumElements) + "]");
  573. return Out << "; }";
  574. }
  575. case Type::OpaqueTyID: {
  576. static int Count = 0;
  577. std::string TyName = "struct opaque_" + itostr(Count++);
  578. assert(TypeNames.find(Ty) == TypeNames.end());
  579. TypeNames[Ty] = TyName;
  580. return Out << TyName << ' ' << NameSoFar;
  581. }
  582. default:
  583. assert(0 && "Unhandled case in getTypeProps!");
  584. abort();
  585. }
  586. return Out;
  587. }
  588. // Pass the Type* and the variable name and this prints out the variable
  589. // declaration.
  590. //
  591. std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
  592. bool isSigned, const std::string &NameSoFar,
  593. bool IgnoreName, const AttrListPtr &PAL) {
  594. if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
  595. printSimpleType(Out, Ty, isSigned, NameSoFar);
  596. return Out;
  597. }
  598. // Check to see if the type is named.
  599. if (!IgnoreName || isa<OpaqueType>(Ty)) {
  600. std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
  601. if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
  602. }
  603. switch (Ty->getTypeID()) {
  604. case Type::FunctionTyID: {
  605. const FunctionType *FTy = cast<FunctionType>(Ty);
  606. std::stringstream FunctionInnards;
  607. FunctionInnards << " (" << NameSoFar << ") (";
  608. unsigned Idx = 1;
  609. for (FunctionType::param_iterator I = FTy->param_begin(),
  610. E = FTy->param_end(); I != E; ++I) {
  611. const Type *ArgTy = *I;
  612. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  613. assert(isa<PointerType>(ArgTy));
  614. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  615. }
  616. if (I != FTy->param_begin())
  617. FunctionInnards << ", ";
  618. printType(FunctionInnards, ArgTy,
  619. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
  620. ++Idx;
  621. }
  622. if (FTy->isVarArg()) {
  623. if (FTy->getNumParams())
  624. FunctionInnards << ", ...";
  625. } else if (!FTy->getNumParams()) {
  626. FunctionInnards << "void";
  627. }
  628. FunctionInnards << ')';
  629. std::string tstr = FunctionInnards.str();
  630. printType(Out, FTy->getReturnType(),
  631. /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
  632. return Out;
  633. }
  634. case Type::StructTyID: {
  635. const StructType *STy = cast<StructType>(Ty);
  636. Out << NameSoFar + " {\n";
  637. unsigned Idx = 0;
  638. for (StructType::element_iterator I = STy->element_begin(),
  639. E = STy->element_end(); I != E; ++I) {
  640. Out << " ";
  641. printType(Out, *I, false, "field" + utostr(Idx++));
  642. Out << ";\n";
  643. }
  644. Out << '}';
  645. if (STy->isPacked())
  646. Out << " __attribute__ ((packed))";
  647. return Out;
  648. }
  649. case Type::PointerTyID: {
  650. const PointerType *PTy = cast<PointerType>(Ty);
  651. std::string ptrName = "*" + NameSoFar;
  652. if (isa<ArrayType>(PTy->getElementType()) ||
  653. isa<VectorType>(PTy->getElementType()))
  654. ptrName = "(" + ptrName + ")";
  655. if (!PAL.isEmpty())
  656. // Must be a function ptr cast!
  657. return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
  658. return printType(Out, PTy->getElementType(), false, ptrName);
  659. }
  660. case Type::ArrayTyID: {
  661. const ArrayType *ATy = cast<ArrayType>(Ty);
  662. unsigned NumElements = ATy->getNumElements();
  663. if (NumElements == 0) NumElements = 1;
  664. // Arrays are wrapped in structs to allow them to have normal
  665. // value semantics (avoiding the array "decay").
  666. Out << NameSoFar << " { ";
  667. printType(Out, ATy->getElementType(), false,
  668. "array[" + utostr(NumElements) + "]");
  669. return Out << "; }";
  670. }
  671. case Type::OpaqueTyID: {
  672. static int Count = 0;
  673. std::string TyName = "struct opaque_" + itostr(Count++);
  674. assert(TypeNames.find(Ty) == TypeNames.end());
  675. TypeNames[Ty] = TyName;
  676. return Out << TyName << ' ' << NameSoFar;
  677. }
  678. default:
  679. assert(0 && "Unhandled case in getTypeProps!");
  680. abort();
  681. }
  682. return Out;
  683. }
  684. void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
  685. // As a special case, print the array as a string if it is an array of
  686. // ubytes or an array of sbytes with positive values.
  687. //
  688. const Type *ETy = CPA->getType()->getElementType();
  689. bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
  690. // Make sure the last character is a null char, as automatically added by C
  691. if (isString && (CPA->getNumOperands() == 0 ||
  692. !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
  693. isString = false;
  694. if (isString) {
  695. Out << '\"';
  696. // Keep track of whether the last number was a hexadecimal escape
  697. bool LastWasHex = false;
  698. // Do not include the last character, which we know is null
  699. for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
  700. unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
  701. // Print it out literally if it is a printable character. The only thing
  702. // to be careful about is when the last letter output was a hex escape
  703. // code, in which case we have to be careful not to print out hex digits
  704. // explicitly (the C compiler thinks it is a continuation of the previous
  705. // character, sheesh...)
  706. //
  707. if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
  708. LastWasHex = false;
  709. if (C == '"' || C == '\\')
  710. Out << "\\" << (char)C;
  711. else
  712. Out << (char)C;
  713. } else {
  714. LastWasHex = false;
  715. switch (C) {
  716. case '\n': Out << "\\n"; break;
  717. case '\t': Out << "\\t"; break;
  718. case '\r': Out << "\\r"; break;
  719. case '\v': Out << "\\v"; break;
  720. case '\a': Out << "\\a"; break;
  721. case '\"': Out << "\\\""; break;
  722. case '\'': Out << "\\\'"; break;
  723. default:
  724. Out << "\\x";
  725. Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
  726. Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
  727. LastWasHex = true;
  728. break;
  729. }
  730. }
  731. }
  732. Out << '\"';
  733. } else {
  734. Out << '{';
  735. if (CPA->getNumOperands()) {
  736. Out << ' ';
  737. printConstant(cast<Constant>(CPA->getOperand(0)), Static);
  738. for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
  739. Out << ", ";
  740. printConstant(cast<Constant>(CPA->getOperand(i)), Static);
  741. }
  742. }
  743. Out << " }";
  744. }
  745. }
  746. void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
  747. Out << '{';
  748. if (CP->getNumOperands()) {
  749. Out << ' ';
  750. printConstant(cast<Constant>(CP->getOperand(0)), Static);
  751. for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
  752. Out << ", ";
  753. printConstant(cast<Constant>(CP->getOperand(i)), Static);
  754. }
  755. }
  756. Out << " }";
  757. }
  758. // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
  759. // textually as a double (rather than as a reference to a stack-allocated
  760. // variable). We decide this by converting CFP to a string and back into a
  761. // double, and then checking whether the conversion results in a bit-equal
  762. // double to the original value of CFP. This depends on us and the target C
  763. // compiler agreeing on the conversion process (which is pretty likely since we
  764. // only deal in IEEE FP).
  765. //
  766. static bool isFPCSafeToPrint(const ConstantFP *CFP) {
  767. bool ignored;
  768. // Do long doubles in hex for now.
  769. if (CFP->getType() != Type::FloatTy && CFP->getType() != Type::DoubleTy)
  770. return false;
  771. APFloat APF = APFloat(CFP->getValueAPF()); // copy
  772. if (CFP->getType() == Type::FloatTy)
  773. APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
  774. #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
  775. char Buffer[100];
  776. sprintf(Buffer, "%a", APF.convertToDouble());
  777. if (!strncmp(Buffer, "0x", 2) ||
  778. !strncmp(Buffer, "-0x", 3) ||
  779. !strncmp(Buffer, "+0x", 3))
  780. return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
  781. return false;
  782. #else
  783. std::string StrVal = ftostr(APF);
  784. while (StrVal[0] == ' ')
  785. StrVal.erase(StrVal.begin());
  786. // Check to make sure that the stringized number is not some string like "Inf"
  787. // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
  788. if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
  789. ((StrVal[0] == '-' || StrVal[0] == '+') &&
  790. (StrVal[1] >= '0' && StrVal[1] <= '9')))
  791. // Reparse stringized version!
  792. return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
  793. return false;
  794. #endif
  795. }
  796. /// Print out the casting for a cast operation. This does the double casting
  797. /// necessary for conversion to the destination type, if necessary.
  798. /// @brief Print a cast
  799. void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
  800. // Print the destination type cast
  801. switch (opc) {
  802. case Instruction::UIToFP:
  803. case Instruction::SIToFP:
  804. case Instruction::IntToPtr:
  805. case Instruction::Trunc:
  806. case Instruction::BitCast:
  807. case Instruction::FPExt:
  808. case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
  809. Out << '(';
  810. printType(Out, DstTy);
  811. Out << ')';
  812. break;
  813. case Instruction::ZExt:
  814. case Instruction::PtrToInt:
  815. case Instruction::FPToUI: // For these, make sure we get an unsigned dest
  816. Out << '(';
  817. printSimpleType(Out, DstTy, false);
  818. Out << ')';
  819. break;
  820. case Instruction::SExt:
  821. case Instruction::FPToSI: // For these, make sure we get a signed dest
  822. Out << '(';
  823. printSimpleType(Out, DstTy, true);
  824. Out << ')';
  825. break;
  826. default:
  827. assert(0 && "Invalid cast opcode");
  828. }
  829. // Print the source type cast
  830. switch (opc) {
  831. case Instruction::UIToFP:
  832. case Instruction::ZExt:
  833. Out << '(';
  834. printSimpleType(Out, SrcTy, false);
  835. Out << ')';
  836. break;
  837. case Instruction::SIToFP:
  838. case Instruction::SExt:
  839. Out << '(';
  840. printSimpleType(Out, SrcTy, true);
  841. Out << ')';
  842. break;
  843. case Instruction::IntToPtr:
  844. case Instruction::PtrToInt:
  845. // Avoid "cast to pointer from integer of different size" warnings
  846. Out << "(unsigned long)";
  847. break;
  848. case Instruction::Trunc:
  849. case Instruction::BitCast:
  850. case Instruction::FPExt:
  851. case Instruction::FPTrunc:
  852. case Instruction::FPToSI:
  853. case Instruction::FPToUI:
  854. break; // These don't need a source cast.
  855. default:
  856. assert(0 && "Invalid cast opcode");
  857. break;
  858. }
  859. }
  860. // printConstant - The LLVM Constant to C Constant converter.
  861. void CWriter::printConstant(Constant *CPV, bool Static) {
  862. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
  863. switch (CE->getOpcode()) {
  864. case Instruction::Trunc:
  865. case Instruction::ZExt:
  866. case Instruction::SExt:
  867. case Instruction::FPTrunc:
  868. case Instruction::FPExt:
  869. case Instruction::UIToFP:
  870. case Instruction::SIToFP:
  871. case Instruction::FPToUI:
  872. case Instruction::FPToSI:
  873. case Instruction::PtrToInt:
  874. case Instruction::IntToPtr:
  875. case Instruction::BitCast:
  876. Out << "(";
  877. printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
  878. if (CE->getOpcode() == Instruction::SExt &&
  879. CE->getOperand(0)->getType() == Type::Int1Ty) {
  880. // Make sure we really sext from bool here by subtracting from 0
  881. Out << "0-";
  882. }
  883. printConstant(CE->getOperand(0), Static);
  884. if (CE->getType() == Type::Int1Ty &&
  885. (CE->getOpcode() == Instruction::Trunc ||
  886. CE->getOpcode() == Instruction::FPToUI ||
  887. CE->getOpcode() == Instruction::FPToSI ||
  888. CE->getOpcode() == Instruction::PtrToInt)) {
  889. // Make sure we really truncate to bool here by anding with 1
  890. Out << "&1u";
  891. }
  892. Out << ')';
  893. return;
  894. case Instruction::GetElementPtr:
  895. Out << "(";
  896. printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
  897. gep_type_end(CPV), Static);
  898. Out << ")";
  899. return;
  900. case Instruction::Select:
  901. Out << '(';
  902. printConstant(CE->getOperand(0), Static);
  903. Out << '?';
  904. printConstant(CE->getOperand(1), Static);
  905. Out << ':';
  906. printConstant(CE->getOperand(2), Static);
  907. Out << ')';
  908. return;
  909. case Instruction::Add:
  910. case Instruction::FAdd:
  911. case Instruction::Sub:
  912. case Instruction::FSub:
  913. case Instruction::Mul:
  914. case Instruction::FMul:
  915. case Instruction::SDiv:
  916. case Instruction::UDiv:
  917. case Instruction::FDiv:
  918. case Instruction::URem:
  919. case Instruction::SRem:
  920. case Instruction::FRem:
  921. case Instruction::And:
  922. case Instruction::Or:
  923. case Instruction::Xor:
  924. case Instruction::ICmp:
  925. case Instruction::Shl:
  926. case Instruction::LShr:
  927. case Instruction::AShr:
  928. {
  929. Out << '(';
  930. bool NeedsClosingParens = printConstExprCast(CE, Static);
  931. printConstantWithCast(CE->getOperand(0), CE->getOpcode());
  932. switch (CE->getOpcode()) {
  933. case Instruction::Add:
  934. case Instruction::FAdd: Out << " + "; break;
  935. case Instruction::Sub:
  936. case Instruction::FSub: Out << " - "; break;
  937. case Instruction::Mul:
  938. case Instruction::FMul: Out << " * "; break;
  939. case Instruction::URem:
  940. case Instruction::SRem:
  941. case Instruction::FRem: Out << " % "; break;
  942. case Instruction::UDiv:
  943. case Instruction::SDiv:
  944. case Instruction::FDiv: Out << " / "; break;
  945. case Instruction::And: Out << " & "; break;
  946. case Instruction::Or: Out << " | "; break;
  947. case Instruction::Xor: Out << " ^ "; break;
  948. case Instruction::Shl: Out << " << "; break;
  949. case Instruction::LShr:
  950. case Instruction::AShr: Out << " >> "; break;
  951. case Instruction::ICmp:
  952. switch (CE->getPredicate()) {
  953. case ICmpInst::ICMP_EQ: Out << " == "; break;
  954. case ICmpInst::ICMP_NE: Out << " != "; break;
  955. case ICmpInst::ICMP_SLT:
  956. case ICmpInst::ICMP_ULT: Out << " < "; break;
  957. case ICmpInst::ICMP_SLE:
  958. case ICmpInst::ICMP_ULE: Out << " <= "; break;
  959. case ICmpInst::ICMP_SGT:
  960. case ICmpInst::ICMP_UGT: Out << " > "; break;
  961. case ICmpInst::ICMP_SGE:
  962. case ICmpInst::ICMP_UGE: Out << " >= "; break;
  963. default: assert(0 && "Illegal ICmp predicate");
  964. }
  965. break;
  966. default: assert(0 && "Illegal opcode here!");
  967. }
  968. printConstantWithCast(CE->getOperand(1), CE->getOpcode());
  969. if (NeedsClosingParens)
  970. Out << "))";
  971. Out << ')';
  972. return;
  973. }
  974. case Instruction::FCmp: {
  975. Out << '(';
  976. bool NeedsClosingParens = printConstExprCast(CE, Static);
  977. if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
  978. Out << "0";
  979. else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
  980. Out << "1";
  981. else {
  982. const char* op = 0;
  983. switch (CE->getPredicate()) {
  984. default: assert(0 && "Illegal FCmp predicate");
  985. case FCmpInst::FCMP_ORD: op = "ord"; break;
  986. case FCmpInst::FCMP_UNO: op = "uno"; break;
  987. case FCmpInst::FCMP_UEQ: op = "ueq"; break;
  988. case FCmpInst::FCMP_UNE: op = "une"; break;
  989. case FCmpInst::FCMP_ULT: op = "ult"; break;
  990. case FCmpInst::FCMP_ULE: op = "ule"; break;
  991. case FCmpInst::FCMP_UGT: op = "ugt"; break;
  992. case FCmpInst::FCMP_UGE: op = "uge"; break;
  993. case FCmpInst::FCMP_OEQ: op = "oeq"; break;
  994. case FCmpInst::FCMP_ONE: op = "one"; break;
  995. case FCmpInst::FCMP_OLT: op = "olt"; break;
  996. case FCmpInst::FCMP_OLE: op = "ole"; break;
  997. case FCmpInst::FCMP_OGT: op = "ogt"; break;
  998. case FCmpInst::FCMP_OGE: op = "oge"; break;
  999. }
  1000. Out << "llvm_fcmp_" << op << "(";
  1001. printConstantWithCast(CE->getOperand(0), CE->getOpcode());
  1002. Out << ", ";
  1003. printConstantWithCast(CE->getOperand(1), CE->getOpcode());
  1004. Out << ")";
  1005. }
  1006. if (NeedsClosingParens)
  1007. Out << "))";
  1008. Out << ')';
  1009. return;
  1010. }
  1011. default:
  1012. cerr << "CWriter Error: Unhandled constant expression: "
  1013. << *CE << "\n";
  1014. abort();
  1015. }
  1016. } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
  1017. Out << "((";
  1018. printType(Out, CPV->getType()); // sign doesn't matter
  1019. Out << ")/*UNDEF*/";
  1020. if (!isa<VectorType>(CPV->getType())) {
  1021. Out << "0)";
  1022. } else {
  1023. Out << "{})";
  1024. }
  1025. return;
  1026. }
  1027. if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
  1028. const Type* Ty = CI->getType();
  1029. if (Ty == Type::Int1Ty)
  1030. Out << (CI->getZExtValue() ? '1' : '0');
  1031. else if (Ty == Type::Int32Ty)
  1032. Out << CI->getZExtValue() << 'u';
  1033. else if (Ty->getPrimitiveSizeInBits() > 32)
  1034. Out << CI->getZExtValue() << "ull";
  1035. else {
  1036. Out << "((";
  1037. printSimpleType(Out, Ty, false) << ')';
  1038. if (CI->isMinValue(true))
  1039. Out << CI->getZExtValue() << 'u';
  1040. else
  1041. Out << CI->getSExtValue();
  1042. Out << ')';
  1043. }
  1044. return;
  1045. }
  1046. switch (CPV->getType()->getTypeID()) {
  1047. case Type::FloatTyID:
  1048. case Type::DoubleTyID:
  1049. case Type::X86_FP80TyID:
  1050. case Type::PPC_FP128TyID:
  1051. case Type::FP128TyID: {
  1052. ConstantFP *FPC = cast<ConstantFP>(CPV);
  1053. std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
  1054. if (I != FPConstantMap.end()) {
  1055. // Because of FP precision problems we must load from a stack allocated
  1056. // value that holds the value in hex.
  1057. Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
  1058. FPC->getType() == Type::DoubleTy ? "double" :
  1059. "long double")
  1060. << "*)&FPConstant" << I->second << ')';
  1061. } else {
  1062. double V;
  1063. if (FPC->getType() == Type::FloatTy)
  1064. V = FPC->getValueAPF().convertToFloat();
  1065. else if (FPC->getType() == Type::DoubleTy)
  1066. V = FPC->getValueAPF().convertToDouble();
  1067. else {
  1068. // Long double. Convert the number to double, discarding precision.
  1069. // This is not awesome, but it at least makes the CBE output somewhat
  1070. // useful.
  1071. APFloat Tmp = FPC->getValueAPF();
  1072. bool LosesInfo;
  1073. Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
  1074. V = Tmp.convertToDouble();
  1075. }
  1076. if (IsNAN(V)) {
  1077. // The value is NaN
  1078. // FIXME the actual NaN bits should be emitted.
  1079. // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
  1080. // it's 0x7ff4.
  1081. const unsigned long QuietNaN = 0x7ff8UL;
  1082. //const unsigned long SignalNaN = 0x7ff4UL;
  1083. // We need to grab the first part of the FP #
  1084. char Buffer[100];
  1085. uint64_t ll = DoubleToBits(V);
  1086. sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
  1087. std::string Num(&Buffer[0], &Buffer[6]);
  1088. unsigned long Val = strtoul(Num.c_str(), 0, 16);
  1089. if (FPC->getType() == Type::FloatTy)
  1090. Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
  1091. << Buffer << "\") /*nan*/ ";
  1092. else
  1093. Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
  1094. << Buffer << "\") /*nan*/ ";
  1095. } else if (IsInf(V)) {
  1096. // The value is Inf
  1097. if (V < 0) Out << '-';
  1098. Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
  1099. << " /*inf*/ ";
  1100. } else {
  1101. std::string Num;
  1102. #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
  1103. // Print out the constant as a floating point number.
  1104. char Buffer[100];
  1105. sprintf(Buffer, "%a", V);
  1106. Num = Buffer;
  1107. #else
  1108. Num = ftostr(FPC->getValueAPF());
  1109. #endif
  1110. Out << Num;
  1111. }
  1112. }
  1113. break;
  1114. }
  1115. case Type::ArrayTyID:
  1116. // Use C99 compound expression literal initializer syntax.
  1117. if (!Static) {
  1118. Out << "(";
  1119. printType(Out, CPV->getType());
  1120. Out << ")";
  1121. }
  1122. Out << "{ "; // Arrays are wrapped in struct types.
  1123. if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
  1124. printConstantArray(CA, Static);
  1125. } else {
  1126. assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
  1127. const ArrayType *AT = cast<ArrayType>(CPV->getType());
  1128. Out << '{';
  1129. if (AT->getNumElements()) {
  1130. Out << ' ';
  1131. Constant *CZ = Constant::getNullValue(AT->getElementType());
  1132. printConstant(CZ, Static);
  1133. for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
  1134. Out << ", ";
  1135. printConstant(CZ, Static);
  1136. }
  1137. }
  1138. Out << " }";
  1139. }
  1140. Out << " }"; // Arrays are wrapped in struct types.
  1141. break;
  1142. case Type::VectorTyID:
  1143. // Use C99 compound expression literal initializer syntax.
  1144. if (!Static) {
  1145. Out << "(";
  1146. printType(Out, CPV->getType());
  1147. Out << ")";
  1148. }
  1149. if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
  1150. printConstantVector(CV, Static);
  1151. } else {
  1152. assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
  1153. const VectorType *VT = cast<VectorType>(CPV->getType());
  1154. Out << "{ ";
  1155. Constant *CZ = Constant::getNullValue(VT->getElementType());
  1156. printConstant(CZ, Static);
  1157. for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
  1158. Out << ", ";
  1159. printConstant(CZ, Static);
  1160. }
  1161. Out << " }";
  1162. }
  1163. break;
  1164. case Type::StructTyID:
  1165. // Use C99 compound expression literal initializer syntax.
  1166. if (!Static) {
  1167. Out << "(";
  1168. printType(Out, CPV->getType());
  1169. Out << ")";
  1170. }
  1171. if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
  1172. const StructType *ST = cast<StructType>(CPV->getType());
  1173. Out << '{';
  1174. if (ST->getNumElements()) {
  1175. Out << ' ';
  1176. printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
  1177. for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
  1178. Out << ", ";
  1179. printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
  1180. }
  1181. }
  1182. Out << " }";
  1183. } else {
  1184. Out << '{';
  1185. if (CPV->getNumOperands()) {
  1186. Out << ' ';
  1187. printConstant(cast<Constant>(CPV->getOperand(0)), Static);
  1188. for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
  1189. Out << ", ";
  1190. printConstant(cast<Constant>(CPV->getOperand(i)), Static);
  1191. }
  1192. }
  1193. Out << " }";
  1194. }
  1195. break;
  1196. case Type::PointerTyID:
  1197. if (isa<ConstantPointerNull>(CPV)) {
  1198. Out << "((";
  1199. printType(Out, CPV->getType()); // sign doesn't matter
  1200. Out << ")/*NULL*/0)";
  1201. break;
  1202. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
  1203. writeOperand(GV, Static);
  1204. break;
  1205. }
  1206. // FALL THROUGH
  1207. default:
  1208. cerr << "Unknown constant type: " << *CPV << "\n";
  1209. abort();
  1210. }
  1211. }
  1212. // Some constant expressions need to be casted back to the original types
  1213. // because their operands were casted to the expected type. This function takes
  1214. // care of detecting that case and printing the cast for the ConstantExpr.
  1215. bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
  1216. bool NeedsExplicitCast = false;
  1217. const Type *Ty = CE->getOperand(0)->getType();
  1218. bool TypeIsSigned = false;
  1219. switch (CE->getOpcode()) {
  1220. case Instruction::Add:
  1221. case Instruction::Sub:
  1222. case Instruction::Mul:
  1223. // We need to cast integer arithmetic so that it is always performed
  1224. // as unsigned, to avoid undefined behavior on overflow.
  1225. case Instruction::LShr:
  1226. case Instruction::URem:
  1227. case Instruction::UDiv: NeedsExplicitCast = true; break;
  1228. case Instruction::AShr:
  1229. case Instruction::SRem:
  1230. case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
  1231. case Instruction::SExt:
  1232. Ty = CE->getType();
  1233. NeedsExplicitCast = true;
  1234. TypeIsSigned = true;
  1235. break;
  1236. case Instruction::ZExt:
  1237. case Instruction::Trunc:
  1238. case Instruction::FPTrunc:
  1239. case Instruction::FPExt:
  1240. case Instruction::UIToFP:
  1241. case Instruction::SIToFP:
  1242. case Instruction::FPToUI:
  1243. case Instruction::FPToSI:
  1244. case Instruction::PtrToInt:
  1245. case Instruction::IntToPtr:
  1246. case Instruction::BitCast:
  1247. Ty = CE->getType();
  1248. NeedsExplicitCast = true;
  1249. break;
  1250. default: break;
  1251. }
  1252. if (NeedsExplicitCast) {
  1253. Out << "((";
  1254. if (Ty->isInteger() && Ty != Type::Int1Ty)
  1255. printSimpleType(Out, Ty, TypeIsSigned);
  1256. else
  1257. printType(Out, Ty); // not integer, sign doesn't matter
  1258. Out << ")(";
  1259. }
  1260. return NeedsExplicitCast;
  1261. }
  1262. // Print a constant assuming that it is the operand for a given Opcode. The
  1263. // opcodes that care about sign need to cast their operands to the expected
  1264. // type before the operation proceeds. This function does the casting.
  1265. void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
  1266. // Extract the operand's type, we'll need it.
  1267. const Type* OpTy = CPV->getType();
  1268. // Indicate whether to do the cast or not.
  1269. bool shouldCast = false;
  1270. bool typeIsSigned = false;
  1271. // Based on the Opcode for which this Constant is being written, determine
  1272. // the new type to which the operand should be casted by setting the value
  1273. // of OpTy. If we change OpTy, also set shouldCast to true so it gets
  1274. // casted below.
  1275. switch (Opcode) {
  1276. default:
  1277. // for most instructions, it doesn't matter
  1278. break;
  1279. case Instruction::Add:
  1280. case Instruction::Sub:
  1281. case Instruction::Mul:
  1282. // We need to cast integer arithmetic so that it is always performed
  1283. // as unsigned, to avoid undefined behavior on overflow.
  1284. case Instruction::LShr:
  1285. case Instruction::UDiv:
  1286. case Instruction::URem:
  1287. shouldCast = true;
  1288. break;
  1289. case Instruction::AShr:
  1290. case Instruction::SDiv:
  1291. case Instruction::SRem:
  1292. shouldCast = true;
  1293. typeIsSigned = true;
  1294. break;
  1295. }
  1296. // Write out the casted constant if we should, otherwise just write the
  1297. // operand.
  1298. if (shouldCast) {
  1299. Out << "((";
  1300. printSimpleType(Out, OpTy, typeIsSigned);
  1301. Out << ")";
  1302. printConstant(CPV, false);
  1303. Out << ")";
  1304. } else
  1305. printConstant(CPV, false);
  1306. }
  1307. std::string CWriter::GetValueName(const Value *Operand) {
  1308. std::string Name;
  1309. if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
  1310. std::string VarName;
  1311. Name = Operand->getName();
  1312. VarName.reserve(Name.capacity());
  1313. for (std::string::iterator I = Name.begin(), E = Name.end();
  1314. I != E; ++I) {
  1315. char ch = *I;
  1316. if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
  1317. (ch >= '0' && ch <= '9') || ch == '_')) {
  1318. char buffer[5];
  1319. sprintf(buffer, "_%x_", ch);
  1320. VarName += buffer;
  1321. } else
  1322. VarName += ch;
  1323. }
  1324. Name = "llvm_cbe_" + VarName;
  1325. } else {
  1326. Name = Mang->getValueName(Operand);
  1327. }
  1328. return Name;
  1329. }
  1330. /// writeInstComputationInline - Emit the computation for the specified
  1331. /// instruction inline, with no destination provided.
  1332. void CWriter::writeInstComputationInline(Instruction &I) {
  1333. // We can't currently support integer types other than 1, 8, 16, 32, 64.
  1334. // Validate this.
  1335. const Type *Ty = I.getType();
  1336. if (Ty->isInteger() && (Ty!=Type::Int1Ty && Ty!=Type::Int8Ty &&
  1337. Ty!=Type::Int16Ty && Ty!=Type::Int32Ty && Ty!=Type::Int64Ty)) {
  1338. cerr << "The C backend does not currently support integer "
  1339. << "types of widths other than 1, 8, 16, 32, 64.\n";
  1340. cerr << "This is being tracked as PR 4158.\n";
  1341. abort();
  1342. }
  1343. // If this is a non-trivial bool computation, make sure to truncate down to
  1344. // a 1 bit value. This is important because we want "add i1 x, y" to return
  1345. // "0" when x and y are true, not "2" for example.
  1346. bool NeedBoolTrunc = false;
  1347. if (I.getType() == Type::Int1Ty && !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
  1348. NeedBoolTrunc = true;
  1349. if (NeedBoolTrunc)
  1350. Out << "((";
  1351. visit(I);
  1352. if (NeedBoolTrunc)
  1353. Out << ")&1)";
  1354. }
  1355. void CWriter::writeOperandInternal(Value *Operand, bool Static) {
  1356. if (Instruction *I = dyn_cast<Instruction>(Operand))
  1357. // Should we inline this instruction to build a tree?
  1358. if (isInlinableInst(*I) && !isDirectAlloca(I)) {
  1359. Out << '(';
  1360. writeInstComputationInline(*I);
  1361. Out << ')';
  1362. return;
  1363. }
  1364. Constant* CPV = dyn_cast<Constant>(Operand);
  1365. if (CPV && !isa<GlobalValue>(CPV))
  1366. printConstant(CPV, Static);
  1367. else
  1368. Out << GetValueName(Operand);
  1369. }
  1370. void CWriter::writeOperand(Value *Operand, bool Static) {
  1371. bool isAddressImplicit = isAddressExposed(Operand);
  1372. if (isAddressImplicit)
  1373. Out << "(&"; // Global variables are referenced as their addresses by llvm
  1374. writeOperandInternal(Operand, Static);
  1375. if (isAddressImplicit)
  1376. Out << ')';
  1377. }
  1378. // Some instructions need to have their result value casted back to the
  1379. // original types because their operands were casted to the expected type.
  1380. // This function takes care of detecting that case and printing the cast
  1381. // for the Instruction.
  1382. bool CWriter::writeInstructionCast(const Instruction &I) {
  1383. const Type *Ty = I.getOperand(0)->getType();
  1384. switch (I.getOpcode()) {
  1385. case Instruction::Add:
  1386. case Instruction::Sub:
  1387. case Instruction::Mul:
  1388. // We need to cast integer arithmetic so that it is always performed
  1389. // as unsigned, to avoid undefined behavior on overflow.
  1390. case Instruction::LShr:
  1391. case Instruction::URem:
  1392. case Instruction::UDiv:
  1393. Out << "((";
  1394. printSimpleType(Out, Ty, false);
  1395. Out << ")(";
  1396. return true;
  1397. case Instruction::AShr:
  1398. case Instruction::SRem:
  1399. case Instruction::SDiv:
  1400. Out << "((";
  1401. printSimpleType(Out, Ty, true);
  1402. Out << ")(";
  1403. return true;
  1404. default: break;
  1405. }
  1406. return false;
  1407. }
  1408. // Write the operand with a cast to another type based on the Opcode being used.
  1409. // This will be used in cases where an instruction has specific type
  1410. // requirements (usually signedness) for its operands.
  1411. void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
  1412. // Extract the operand's type, we'll need it.
  1413. const Type* OpTy = Operand->getType();
  1414. // Indicate whether to do the cast or not.
  1415. bool shouldCast = false;
  1416. // Indicate whether the cast should be to a signed type or not.
  1417. bool castIsSigned = false;
  1418. // Based on the Opcode for which this Operand is being written, determine
  1419. // the new type to which the operand should be casted by setting the value
  1420. // of OpTy. If we change OpTy, also set shouldCast to true.
  1421. switch (Opcode) {
  1422. default:
  1423. // for most instructions, it doesn't matter
  1424. break;
  1425. case Instruction::Add:
  1426. case Instruction::Sub:
  1427. case Instruction::Mul:
  1428. // We need to cast integer arithmetic so that it is always performed
  1429. // as unsigned, to avoid undefined behavior on overflow.
  1430. case Instruction::LShr:
  1431. case Instruction::UDiv:
  1432. case Instruction::URem: // Cast to unsigned first
  1433. shouldCast = true;
  1434. castIsSigned = false;
  1435. break;
  1436. case Instruction::GetElementPtr:
  1437. case Instruction::AShr:
  1438. case Instruction::SDiv:
  1439. case Instruction::SRem: // Cast to signed first
  1440. shouldCast = true;
  1441. castIsSigned = true;
  1442. break;
  1443. }
  1444. // Write out the casted operand if we should, otherwise just write the
  1445. // operand.
  1446. if (shouldCast) {
  1447. Out << "((";
  1448. printSimpleType(Out, OpTy, castIsSigned);
  1449. Out << ")";
  1450. writeOperand(Operand);
  1451. Out << ")";
  1452. } else
  1453. writeOperand(Operand);
  1454. }
  1455. // Write the operand with a cast to another type based on the icmp predicate
  1456. // being used.
  1457. void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
  1458. // This has to do a cast to ensure the operand has the right signedness.
  1459. // Also, if the operand is a pointer, we make sure to cast to an integer when
  1460. // doing the comparison both for signedness and so that the C compiler doesn't
  1461. // optimize things like "p < NULL" to false (p may contain an integer value
  1462. // f.e.).
  1463. bool shouldCast = Cmp.isRelational();
  1464. // Write out the casted operand if we should, otherwise just write the
  1465. // operand.
  1466. if (!shouldCast) {
  1467. writeOperand(Operand);
  1468. return;
  1469. }
  1470. // Should this be a signed comparison? If so, convert to signed.
  1471. bool castIsSigned = Cmp.isSignedPredicate();
  1472. // If the operand was a pointer, convert to a large integer type.
  1473. const Type* OpTy = Operand->getType();
  1474. if (isa<PointerType>(OpTy))
  1475. OpTy = TD->getIntPtrType();
  1476. Out << "((";
  1477. printSimpleType(Out, OpTy, castIsSigned);
  1478. Out << ")";
  1479. writeOperand(Operand);
  1480. Out << ")";
  1481. }
  1482. // generateCompilerSpecificCode - This is where we add conditional compilation
  1483. // directives to cater to specific compilers as need be.
  1484. //
  1485. static void generateCompilerSpecificCode(raw_ostream& Out,
  1486. const TargetData *TD) {
  1487. // Alloca is hard to get, and we don't want to include stdlib.h here.
  1488. Out << "/* get a declaration for alloca */\n"
  1489. << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
  1490. << "#define alloca(x) __builtin_alloca((x))\n"
  1491. << "#define _alloca(x) __builtin_alloca((x))\n"
  1492. << "#elif defined(__APPLE__)\n"
  1493. << "extern void *__builtin_alloca(unsigned long);\n"
  1494. << "#define alloca(x) __builtin_alloca(x)\n"
  1495. << "#define longjmp _longjmp\n"
  1496. << "#define setjmp _setjmp\n"
  1497. << "#elif defined(__sun__)\n"
  1498. << "#if defined(__sparcv9)\n"
  1499. << "extern void *__builtin_alloca(unsigned long);\n"
  1500. << "#else\n"
  1501. << "extern void *__builtin_alloca(unsigned int);\n"
  1502. << "#endif\n"
  1503. << "#define alloca(x) __builtin_alloca(x)\n"
  1504. << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)\n"
  1505. << "#define alloca(x) __builtin_alloca(x)\n"
  1506. << "#elif defined(_MSC_VER)\n"
  1507. << "#define inline _inline\n"
  1508. << "#define alloca(x) _alloca(x)\n"
  1509. << "#else\n"
  1510. << "#include <alloca.h>\n"
  1511. << "#endif\n\n";
  1512. // We output GCC specific attributes to preserve 'linkonce'ness on globals.
  1513. // If we aren't being compiled with GCC, just drop these attributes.
  1514. Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
  1515. << "#define __attribute__(X)\n"
  1516. << "#endif\n\n";
  1517. // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
  1518. Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
  1519. << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
  1520. << "#elif defined(__GNUC__)\n"
  1521. << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
  1522. << "#else\n"
  1523. << "#define __EXTERNAL_WEAK__\n"
  1524. << "#endif\n\n";
  1525. // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
  1526. Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
  1527. << "#define __ATTRIBUTE_WEAK__\n"
  1528. << "#elif defined(__GNUC__)\n"
  1529. << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
  1530. << "#else\n"
  1531. << "#define __ATTRIBUTE_WEAK__\n"
  1532. << "#endif\n\n";
  1533. // Add hidden visibility support. FIXME: APPLE_CC?
  1534. Out << "#if defined(__GNUC__)\n"
  1535. << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
  1536. << "#endif\n\n";
  1537. // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
  1538. // From the GCC documentation:
  1539. //
  1540. // double __builtin_nan (const char *str)
  1541. //
  1542. // This is an implementation of the ISO C99 function nan.
  1543. //
  1544. // Since ISO C99 defines this function in terms of strtod, which we do
  1545. // not implement, a description of the parsing is in order. The string is
  1546. // parsed as by strtol; that is, the base is recognized by leading 0 or
  1547. // 0x prefixes. The number parsed is placed in the significand such that
  1548. // the least significant bit of the number is at the least significant
  1549. // bit of the significand. The number is truncated to fit the significand
  1550. // field provided. The significand is forced to be a quiet NaN.
  1551. //
  1552. // This function, if given a string literal, is evaluated early enough
  1553. // that it is considered a compile-time constant.
  1554. //
  1555. // float __builtin_nanf (const char *str)
  1556. //
  1557. // Similar to __builtin_nan, except the return type is float.
  1558. //
  1559. // double __builtin_inf (void)
  1560. //
  1561. // Similar to __builtin_huge_val, except a warning is generated if the
  1562. // target floating-point format does not support infinities. This
  1563. // function is suitable for implementing the ISO C99 macro INFINITY.
  1564. //
  1565. // float __builtin_inff (void)
  1566. //
  1567. // Similar to __builtin_inf, except the return type is float.
  1568. Out << "#ifdef __GNUC__\n"
  1569. << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
  1570. << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
  1571. << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
  1572. << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
  1573. << "#define LLVM_INF __builtin_inf() /* Double */\n"
  1574. << "#define LLVM_INFF __builtin_inff() /* Float */\n"
  1575. << "#define LLVM_PREFETCH(addr,rw,locality) "
  1576. "__builtin_prefetch(addr,rw,locality)\n"
  1577. << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
  1578. << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
  1579. << "#define LLVM_ASM __asm__\n"
  1580. << "#else\n"
  1581. << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
  1582. << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
  1583. << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
  1584. << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
  1585. << "#define LLVM_INF ((double)0.0) /* Double */\n"
  1586. << "#define LLVM_INFF 0.0F /* Float */\n"
  1587. << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
  1588. << "#define __ATTRIBUTE_CTOR__\n"
  1589. << "#define __ATTRIBUTE_DTOR__\n"
  1590. << "#define LLVM_ASM(X)\n"
  1591. << "#endif\n\n";
  1592. Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
  1593. << "#define __builtin_stack_save() 0 /* not implemented */\n"
  1594. << "#define __builtin_stack_restore(X) /* noop */\n"
  1595. << "#endif\n\n";
  1596. // Output typedefs for 128-bit integers. If these are needed with a
  1597. // 32-bit target or with a C compiler that doesn't support mode(TI),
  1598. // more drastic measures will be needed.
  1599. Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
  1600. << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
  1601. << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
  1602. << "#endif\n\n";
  1603. // Output target-specific code that should be inserted into main.
  1604. Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
  1605. }
  1606. /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
  1607. /// the StaticTors set.
  1608. static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
  1609. ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
  1610. if (!InitList) return;
  1611. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
  1612. if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
  1613. if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
  1614. if (CS->getOperand(1)->isNullValue())
  1615. return; // Found a null terminator, exit printing.
  1616. Constant *FP = CS->getOperand(1);
  1617. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
  1618. if (CE->isCast())
  1619. FP = CE->getOperand(0);
  1620. if (Function *F = dyn_cast<Function>(FP))
  1621. StaticTors.insert(F);
  1622. }
  1623. }
  1624. enum SpecialGlobalClass {
  1625. NotSpecial = 0,
  1626. GlobalCtors, GlobalDtors,
  1627. NotPrinted
  1628. };
  1629. /// getGlobalVariableClass - If this is a global that is specially recognized
  1630. /// by LLVM, return a code that indicates how we should handle it.
  1631. static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
  1632. // If this is a global ctors/dtors list, handle it now.
  1633. if (GV->hasAppendingLinkage() && GV->use_empty()) {
  1634. if (GV->getName() == "llvm.global_ctors")
  1635. return GlobalCtors;
  1636. else if (GV->getName() == "llvm.global_dtors")
  1637. return GlobalDtors;
  1638. }
  1639. // Otherwise, it it is other metadata, don't print it. This catches things
  1640. // like debug information.
  1641. if (GV->getSection() == "llvm.metadata")
  1642. return NotPrinted;
  1643. return NotSpecial;
  1644. }
  1645. bool CWriter::doInitialization(Module &M) {
  1646. // Initialize
  1647. TheModule = &M;
  1648. TD = new TargetData(&M);
  1649. IL = new IntrinsicLowering(*TD);
  1650. IL->AddPrototypes(M);
  1651. // Ensure that all structure types have names...
  1652. Mang = new Mangler(M);
  1653. Mang->markCharUnacceptable('.');
  1654. // Keep track of which functions are static ctors/dtors so they can have
  1655. // an attribute added to their prototypes.
  1656. std::set<Function*> StaticCtors, StaticDtors;
  1657. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  1658. I != E; ++I) {
  1659. switch (getGlobalVariableClass(I)) {
  1660. default: break;
  1661. case GlobalCtors:
  1662. FindStaticTors(I, StaticCtors);
  1663. break;
  1664. case GlobalDtors:
  1665. FindStaticTors(I, StaticDtors);
  1666. break;
  1667. }
  1668. }
  1669. // get declaration for alloca
  1670. Out << "/* Provide Declarations */\n";
  1671. Out << "#include <stdarg.h>\n"; // Varargs support
  1672. Out << "#include <setjmp.h>\n"; // Unwind support
  1673. generateCompilerSpecificCode(Out, TD);
  1674. // Provide a definition for `bool' if not compiling with a C++ compiler.
  1675. Out << "\n"
  1676. << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
  1677. << "\n\n/* Support for floating point constants */\n"
  1678. << "typedef unsigned long long ConstantDoubleTy;\n"
  1679. << "typedef unsigned int ConstantFloatTy;\n"
  1680. << "typedef struct { unsigned long long f1; unsigned short f2; "
  1681. "unsigned short pad[3]; } ConstantFP80Ty;\n"
  1682. // This is used for both kinds of 128-bit long double; meaning differs.
  1683. << "typedef struct { unsigned long long f1; unsigned long long f2; }"
  1684. " ConstantFP128Ty;\n"
  1685. << "\n\n/* Global Declarations */\n";
  1686. // First output all the declarations for the program, because C requires
  1687. // Functions & globals to be declared before they are used.
  1688. //
  1689. // Loop over the symbol table, emitting all named constants...
  1690. printModuleTypes(M.getTypeSymbolTable());
  1691. // Global variable declarations...
  1692. if (!M.global_empty()) {
  1693. Out << "\n/* External Global Variable Declarations */\n";
  1694. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  1695. I != E; ++I) {
  1696. if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
  1697. I->hasCommonLinkage())
  1698. Out << "extern ";
  1699. else if (I->hasDLLImportLinkage())
  1700. Out << "__declspec(dllimport) ";
  1701. else
  1702. continue; // Internal Global
  1703. // Thread Local Storage
  1704. if (I->isThreadLocal())
  1705. Out << "__thread ";
  1706. printType(Out, I->getType()->getElementType(), false, GetValueName(I));
  1707. if (I->hasExternalWeakLinkage())
  1708. Out << " __EXTERNAL_WEAK__";
  1709. Out << ";\n";
  1710. }
  1711. }
  1712. // Function declarations
  1713. Out << "\n/* Function Declarations */\n";
  1714. Out << "double fmod(double, double);\n"; // Support for FP rem
  1715. Out << "float fmodf(float, float);\n";
  1716. Out << "long double fmodl(long double, long double);\n";
  1717. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
  1718. // Don't print declarations for intrinsic functions.
  1719. if (!I->isIntrinsic() && I->getName() != "setjmp" &&
  1720. I->getName() != "longjmp" && I->getName() != "_setjmp") {
  1721. if (I->hasExternalWeakLinkage())
  1722. Out << "extern ";
  1723. printFunctionSignature(I, true);
  1724. if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
  1725. Out << " __ATTRIBUTE_WEAK__";
  1726. if (I->hasExternalWeakLinkage())
  1727. Out << " __EXTERNAL_WEAK__";
  1728. if (StaticCtors.count(I))
  1729. Out << " __ATTRIBUTE_CTOR__";
  1730. if (StaticDtors.count(I))
  1731. Out << " __ATTRIBUTE_DTOR__";
  1732. if (I->hasHiddenVisibility())
  1733. Out << " __HIDDEN__";
  1734. if (I->hasName() && I->getName()[0] == 1)
  1735. Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
  1736. Out << ";\n";
  1737. }
  1738. }
  1739. // Output the global variable declarations
  1740. if (!M.global_empty()) {
  1741. Out << "\n\n/* Global Variable Declarations */\n";
  1742. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  1743. I != E; ++I)
  1744. if (!I->isDeclaration()) {
  1745. // Ignore special globals, such as debug info.
  1746. if (getGlobalVariableClass(I))
  1747. continue;
  1748. if (I->hasLocalLinkage())
  1749. Out << "static ";
  1750. else
  1751. Out << "extern ";
  1752. // Thread Local Storage
  1753. if (I->isThreadLocal())
  1754. Out << "__thread ";
  1755. printType(Out, I->getType()->getElementType(), false,
  1756. GetValueName(I));
  1757. if (I->hasLinkOnceLinkage())
  1758. Out << " __attribute__((common))";
  1759. else if (I->hasCommonLinkage()) // FIXME is this right?
  1760. Out << " __ATTRIBUTE_WEAK__";
  1761. else if (I->hasWeakLinkage())
  1762. Out << " __ATTRIBUTE_WEAK__";
  1763. else if (I->hasExternalWeakLinkage())
  1764. Out << " __EXTERNAL_WEAK__";
  1765. if (I->hasHiddenVisibility())
  1766. Out << " __HIDDEN__";
  1767. Out << ";\n";
  1768. }
  1769. }
  1770. // Output the global variable definitions and contents...
  1771. if (!M.global_empty()) {
  1772. Out << "\n\n/* Global Variable Definitions and Initialization */\n";
  1773. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  1774. I != E; ++I)
  1775. if (!I->isDeclaration()) {
  1776. // Ignore special globals, such as debug info.
  1777. if (getGlobalVariableClass(I))
  1778. continue;
  1779. if (I->hasLocalLinkage())
  1780. Out << "static ";
  1781. else if (I->hasDLLImportLinkage())
  1782. Out << "__declspec(dllimport) ";
  1783. else if (I->hasDLLExportLinkage())
  1784. Out << "__declspec(dllexport) ";
  1785. // Thread Local Storage
  1786. if (I->isThreadLocal())
  1787. Out << "__thread ";
  1788. printType(Out, I->getType()->getElementType(), false,
  1789. GetValueName(I));
  1790. if (I->hasLinkOnceLinkage())
  1791. Out << " __attribute__((common))";
  1792. else if (I->hasWeakLinkage())
  1793. Out << " __ATTRIBUTE_WEAK__";
  1794. else if (I->hasCommonLinkage())
  1795. Out << " __ATTRIBUTE_WEAK__";
  1796. if (I->hasHiddenVisibility())
  1797. Out << " __HIDDEN__";
  1798. // If the initializer is not null, emit the initializer. If it is null,
  1799. // we try to avoid emitting large amounts of zeros. The problem with
  1800. // this, however, occurs when the variable has weak linkage. In this
  1801. // case, the assembler will complain about the variable being both weak
  1802. // and common, so we disable this optimization.
  1803. // FIXME common linkage should avoid this problem.
  1804. if (!I->getInitializer()->isNullValue()) {
  1805. Out << " = " ;
  1806. writeOperand(I->getInitializer(), true);
  1807. } else if (I->hasWeakLinkage()) {
  1808. // We have to specify an initializer, but it doesn't have to be
  1809. // complete. If the value is an aggregate, print out { 0 }, and let
  1810. // the compiler figure out the rest of the zeros.
  1811. Out << " = " ;
  1812. if (isa<StructType>(I->getInitializer()->getType()) ||
  1813. isa<VectorType>(I->getInitializer()->getType())) {
  1814. Out << "{ 0 }";
  1815. } else if (isa<ArrayType>(I->getInitializer()->getType())) {
  1816. // As with structs and vectors, but with an extra set of braces
  1817. // because arrays are wrapped in structs.
  1818. Out << "{ { 0 } }";
  1819. } else {
  1820. // Just print it out normally.
  1821. writeOperand(I->getInitializer(), true);
  1822. }
  1823. }
  1824. Out << ";\n";
  1825. }
  1826. }
  1827. if (!M.empty())
  1828. Out << "\n\n/* Function Bodies */\n";
  1829. // Emit some helper functions for dealing with FCMP instruction's
  1830. // predicates
  1831. Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
  1832. Out << "return X == X && Y == Y; }\n";
  1833. Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
  1834. Out << "return X != X || Y != Y; }\n";
  1835. Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
  1836. Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
  1837. Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
  1838. Out << "return X != Y; }\n";
  1839. Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
  1840. Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
  1841. Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
  1842. Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
  1843. Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
  1844. Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
  1845. Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
  1846. Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
  1847. Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
  1848. Out << "return X == Y ; }\n";
  1849. Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
  1850. Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
  1851. Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
  1852. Out << "return X < Y ; }\n";
  1853. Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
  1854. Out << "return X > Y ; }\n";
  1855. Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
  1856. Out << "return X <= Y ; }\n";
  1857. Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
  1858. Out << "return X >= Y ; }\n";
  1859. return false;
  1860. }
  1861. /// Output all floating point constants that cannot be printed accurately...
  1862. void CWriter::printFloatingPointConstants(Function &F) {
  1863. // Scan the module for floating point constants. If any FP constant is used
  1864. // in the function, we want to redirect it here so that we do not depend on
  1865. // the precision of the printed form, unless the printed form preserves
  1866. // precision.
  1867. //
  1868. for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
  1869. I != E; ++I)
  1870. printFloatingPointConstants(*I);
  1871. Out << '\n';
  1872. }
  1873. void CWriter::printFloatingPointConstants(const Constant *C) {
  1874. // If this is a constant expression, recursively check for constant fp values.
  1875. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1876. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
  1877. printFloatingPointConstants(CE->getOperand(i));
  1878. return;
  1879. }
  1880. // Otherwise, check for a FP constant that we need to print.
  1881. const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
  1882. if (FPC == 0 ||
  1883. // Do not put in FPConstantMap if safe.
  1884. isFPCSafeToPrint(FPC) ||
  1885. // Already printed this constant?
  1886. FPConstantMap.count(FPC))
  1887. return;
  1888. FPConstantMap[FPC] = FPCounter; // Number the FP constants
  1889. if (FPC->getType() == Type::DoubleTy) {
  1890. double Val = FPC->getValueAPF().convertToDouble();
  1891. uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
  1892. Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
  1893. << " = 0x" << utohexstr(i)
  1894. << "ULL; /* " << Val << " */\n";
  1895. } else if (FPC->getType() == Type::FloatTy) {
  1896. float Val = FPC->getValueAPF().convertToFloat();
  1897. uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
  1898. getZExtValue();
  1899. Out << "static const ConstantFloatTy FPConstant" << FPCounter++
  1900. << " = 0x" << utohexstr(i)
  1901. << "U; /* " << Val << " */\n";
  1902. } else if (FPC->getType() == Type::X86_FP80Ty) {
  1903. // api needed to prevent premature destruction
  1904. APInt api = FPC->getValueAPF().bitcastToAPInt();
  1905. const uint64_t *p = api.getRawData();
  1906. Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
  1907. << " = { 0x" << utohexstr(p[0])
  1908. << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
  1909. << "}; /* Long double constant */\n";
  1910. } else if (FPC->getType() == Type::PPC_FP128Ty) {
  1911. APInt api = FPC->getValueAPF().bitcastToAPInt();
  1912. const uint64_t *p = api.getRawData();
  1913. Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
  1914. << " = { 0x"
  1915. << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
  1916. << "}; /* Long double constant */\n";
  1917. } else {
  1918. assert(0 && "Unknown float type!");
  1919. }
  1920. }
  1921. /// printSymbolTable - Run through symbol table looking for type names. If a
  1922. /// type name is found, emit its declaration...
  1923. ///
  1924. void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
  1925. Out << "/* Helper union for bitcasts */\n";
  1926. Out << "typedef union {\n";
  1927. Out << " unsigned int Int32;\n";
  1928. Out << " unsigned long long Int64;\n";
  1929. Out << " float Float;\n";
  1930. Out << " double Double;\n";
  1931. Out << "} llvmBitCastUnion;\n";
  1932. // We are only interested in the type plane of the symbol table.
  1933. TypeSymbolTable::const_iterator I = TST.begin();
  1934. TypeSymbolTable::const_iterator End = TST.end();
  1935. // If there are no type names, exit early.
  1936. if (I == End) return;
  1937. // Print out forward declarations for structure types before anything else!
  1938. Out << "/* Structure forward decls */\n";
  1939. for (; I != End; ++I) {
  1940. std::string Name = "struct l_" + Mang->makeNameProper(I->first);
  1941. Out << Name << ";\n";
  1942. TypeNames.insert(std::make_pair(I->second, Name));
  1943. }
  1944. Out << '\n';
  1945. // Now we can print out typedefs. Above, we guaranteed that this can only be
  1946. // for struct or opaque types.
  1947. Out << "/* Typedefs */\n";
  1948. for (I = TST.begin(); I != End; ++I) {
  1949. std::string Name = "l_" + Mang->makeNameProper(I->first);
  1950. Out << "typedef ";
  1951. printType(Out, I->second, false, Name);
  1952. Out << ";\n";
  1953. }
  1954. Out << '\n';
  1955. // Keep track of which structures have been printed so far...
  1956. std::set<const Type *> StructPrinted;
  1957. // Loop over all structures then push them into the stack so they are
  1958. // printed in the correct order.
  1959. //
  1960. Out << "/* Structure contents */\n";
  1961. for (I = TST.begin(); I != End; ++I)
  1962. if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
  1963. // Only print out used types!
  1964. printContainedStructs(I->second, StructPrinted);
  1965. }
  1966. // Push the struct onto the stack and recursively push all structs
  1967. // this one depends on.
  1968. //
  1969. // TODO: Make this work properly with vector types
  1970. //
  1971. void CWriter::printContainedStructs(const Type *Ty,
  1972. std::set<const Type*> &StructPrinted) {
  1973. // Don't walk through pointers.
  1974. if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
  1975. // Print all contained types first.
  1976. for (Type::subtype_iterator I = Ty->subtype_begin(),
  1977. E = Ty->subtype_end(); I != E; ++I)
  1978. printContainedStructs(*I, StructPrinted);
  1979. if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
  1980. // Check to see if we have already printed this struct.
  1981. if (StructPrinted.insert(Ty).second) {
  1982. // Print structure type out.
  1983. std::string Name = TypeNames[Ty];
  1984. printType(Out, Ty, false, Name, true);
  1985. Out << ";\n\n";
  1986. }
  1987. }
  1988. }
  1989. void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
  1990. /// isStructReturn - Should this function actually return a struct by-value?
  1991. bool isStructReturn = F->hasStructRetAttr();
  1992. if (F->hasLocalLinkage()) Out << "static ";
  1993. if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
  1994. if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
  1995. switch (F->getCallingConv()) {
  1996. case CallingConv::X86_StdCall:
  1997. Out << "__attribute__((stdcall)) ";
  1998. break;
  1999. case CallingConv::X86_FastCall:
  2000. Out << "__attribute__((fastcall)) ";
  2001. break;
  2002. }
  2003. // Loop over the arguments, printing them...
  2004. const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
  2005. const AttrListPtr &PAL = F->getAttributes();
  2006. std::stringstream FunctionInnards;
  2007. // Print out the name...
  2008. FunctionInnards << GetValueName(F) << '(';
  2009. bool PrintedArg = false;
  2010. if (!F->isDeclaration()) {
  2011. if (!F->arg_empty()) {
  2012. Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  2013. unsigned Idx = 1;
  2014. // If this is a struct-return function, don't print the hidden
  2015. // struct-return argument.
  2016. if (isStructReturn) {
  2017. assert(I != E && "Invalid struct return function!");
  2018. ++I;
  2019. ++Idx;
  2020. }
  2021. std::string ArgName;
  2022. for (; I != E; ++I) {
  2023. if (PrintedArg) FunctionInnards << ", ";
  2024. if (I->hasName() || !Prototype)
  2025. ArgName = GetValueName(I);
  2026. else
  2027. ArgName = "";
  2028. const Type *ArgTy = I->getType();
  2029. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  2030. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  2031. ByValParams.insert(I);
  2032. }
  2033. printType(FunctionInnards, ArgTy,
  2034. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
  2035. ArgName);
  2036. PrintedArg = true;
  2037. ++Idx;
  2038. }
  2039. }
  2040. } else {
  2041. // Loop over the arguments, printing them.
  2042. FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
  2043. unsigned Idx = 1;
  2044. // If this is a struct-return function, don't print the hidden
  2045. // struct-return argument.
  2046. if (isStructReturn) {
  2047. assert(I != E && "Invalid struct return function!");
  2048. ++I;
  2049. ++Idx;
  2050. }
  2051. for (; I != E; ++I) {
  2052. if (PrintedArg) FunctionInnards << ", ";
  2053. const Type *ArgTy = *I;
  2054. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  2055. assert(isa<PointerType>(ArgTy));
  2056. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  2057. }
  2058. printType(FunctionInnards, ArgTy,
  2059. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
  2060. PrintedArg = true;
  2061. ++Idx;
  2062. }
  2063. }
  2064. // Finish printing arguments... if this is a vararg function, print the ...,
  2065. // unless there are no known types, in which case, we just emit ().
  2066. //
  2067. if (FT->isVarArg() && PrintedArg) {
  2068. if (PrintedArg) FunctionInnards << ", ";
  2069. FunctionInnards << "..."; // Output varargs portion of signature!
  2070. } else if (!FT->isVarArg() && !PrintedArg) {
  2071. FunctionInnards << "void"; // ret() -> ret(void) in C.
  2072. }
  2073. FunctionInnards << ')';
  2074. // Get the return tpe for the function.
  2075. const Type *RetTy;
  2076. if (!isStructReturn)
  2077. RetTy = F->getReturnType();
  2078. else {
  2079. // If this is a struct-return function, print the struct-return type.
  2080. RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
  2081. }
  2082. // Print out the return type and the signature built above.
  2083. printType(Out, RetTy,
  2084. /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
  2085. FunctionInnards.str());
  2086. }
  2087. static inline bool isFPIntBitCast(const Instruction &I) {
  2088. if (!isa<BitCastInst>(I))
  2089. return false;
  2090. const Type *SrcTy = I.getOperand(0)->getType();
  2091. const Type *DstTy = I.getType();
  2092. return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
  2093. (DstTy->isFloatingPoint() && SrcTy->isInteger());
  2094. }
  2095. void CWriter::printFunction(Function &F) {
  2096. /// isStructReturn - Should this function actually return a struct by-value?
  2097. bool isStructReturn = F.hasStructRetAttr();
  2098. printFunctionSignature(&F, false);
  2099. Out << " {\n";
  2100. // If this is a struct return function, handle the result with magic.
  2101. if (isStructReturn) {
  2102. const Type *StructTy =
  2103. cast<PointerType>(F.arg_begin()->getType())->getElementType();
  2104. Out << " ";
  2105. printType(Out, StructTy, false, "StructReturn");
  2106. Out << "; /* Struct return temporary */\n";
  2107. Out << " ";
  2108. printType(Out, F.arg_begin()->getType(), false,
  2109. GetValueName(F.arg_begin()));
  2110. Out << " = &StructReturn;\n";
  2111. }
  2112. bool PrintedVar = false;
  2113. // print local variable information for the function
  2114. for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
  2115. if (const AllocaInst *AI = isDirectAlloca(&*I)) {
  2116. Out << " ";
  2117. printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
  2118. Out << "; /* Address-exposed local */\n";
  2119. PrintedVar = true;
  2120. } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
  2121. Out << " ";
  2122. printType(Out, I->getType(), false, GetValueName(&*I));
  2123. Out << ";\n";
  2124. if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
  2125. Out << " ";
  2126. printType(Out, I->getType(), false,
  2127. GetValueName(&*I)+"__PHI_TEMPORARY");
  2128. Out << ";\n";
  2129. }
  2130. PrintedVar = true;
  2131. }
  2132. // We need a temporary for the BitCast to use so it can pluck a value out
  2133. // of a union to do the BitCast. This is separate from the need for a
  2134. // variable to hold the result of the BitCast.
  2135. if (isFPIntBitCast(*I)) {
  2136. Out << " llvmBitCastUnion " << GetValueName(&*I)
  2137. << "__BITCAST_TEMPORARY;\n";
  2138. PrintedVar = true;
  2139. }
  2140. }
  2141. if (PrintedVar)
  2142. Out << '\n';
  2143. if (F.hasExternalLinkage() && F.getName() == "main")
  2144. Out << " CODE_FOR_MAIN();\n";
  2145. // print the basic blocks
  2146. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  2147. if (Loop *L = LI->getLoopFor(BB)) {
  2148. if (L->getHeader() == BB && L->getParentLoop() == 0)
  2149. printLoop(L);
  2150. } else {
  2151. printBasicBlock(BB);
  2152. }
  2153. }
  2154. Out << "}\n\n";
  2155. }
  2156. void CWriter::printLoop(Loop *L) {
  2157. Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
  2158. << "' to make GCC happy */\n";
  2159. for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
  2160. BasicBlock *BB = L->getBlocks()[i];
  2161. Loop *BBLoop = LI->getLoopFor(BB);
  2162. if (BBLoop == L)
  2163. printBasicBlock(BB);
  2164. else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
  2165. printLoop(BBLoop);
  2166. }
  2167. Out << " } while (1); /* end of syntactic loop '"
  2168. << L->getHeader()->getName() << "' */\n";
  2169. }
  2170. void CWriter::printBasicBlock(BasicBlock *BB) {
  2171. // Don't print the label for the basic block if there are no uses, or if
  2172. // the only terminator use is the predecessor basic block's terminator.
  2173. // We have to scan the use list because PHI nodes use basic blocks too but
  2174. // do not require a label to be generated.
  2175. //
  2176. bool NeedsLabel = false;
  2177. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  2178. if (isGotoCodeNecessary(*PI, BB)) {
  2179. NeedsLabel = true;
  2180. break;
  2181. }
  2182. if (NeedsLabel) Out << GetValueName(BB) << ":\n";
  2183. // Output all of the instructions in the basic block...
  2184. for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
  2185. ++II) {
  2186. if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
  2187. if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
  2188. outputLValue(II);
  2189. else
  2190. Out << " ";
  2191. writeInstComputationInline(*II);
  2192. Out << ";\n";
  2193. }
  2194. }
  2195. // Don't emit prefix or suffix for the terminator.
  2196. visit(*BB->getTerminator());
  2197. }
  2198. // Specific Instruction type classes... note that all of the casts are
  2199. // necessary because we use the instruction classes as opaque types...
  2200. //
  2201. void CWriter::visitReturnInst(ReturnInst &I) {
  2202. // If this is a struct return function, return the temporary struct.
  2203. bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
  2204. if (isStructReturn) {
  2205. Out << " return StructReturn;\n";
  2206. return;
  2207. }
  2208. // Don't output a void return if this is the last basic block in the function
  2209. if (I.getNumOperands() == 0 &&
  2210. &*--I.getParent()->getParent()->end() == I.getParent() &&
  2211. !I.getParent()->size() == 1) {
  2212. return;
  2213. }
  2214. if (I.getNumOperands() > 1) {
  2215. Out << " {\n";
  2216. Out << " ";
  2217. printType(Out, I.getParent()->getParent()->getReturnType());
  2218. Out << " llvm_cbe_mrv_temp = {\n";
  2219. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
  2220. Out << " ";
  2221. writeOperand(I.getOperand(i));
  2222. if (i != e - 1)
  2223. Out << ",";
  2224. Out << "\n";
  2225. }
  2226. Out << " };\n";
  2227. Out << " return llvm_cbe_mrv_temp;\n";
  2228. Out << " }\n";
  2229. return;
  2230. }
  2231. Out << " return";
  2232. if (I.getNumOperands()) {
  2233. Out << ' ';
  2234. writeOperand(I.getOperand(0));
  2235. }
  2236. Out << ";\n";
  2237. }
  2238. void CWriter::visitSwitchInst(SwitchInst &SI) {
  2239. Out << " switch (";
  2240. writeOperand(SI.getOperand(0));
  2241. Out << ") {\n default:\n";
  2242. printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
  2243. printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
  2244. Out << ";\n";
  2245. for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
  2246. Out << " case ";
  2247. writeOperand(SI.getOperand(i));
  2248. Out << ":\n";
  2249. BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
  2250. printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
  2251. printBranchToBlock(SI.getParent(), Succ, 2);
  2252. if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
  2253. Out << " break;\n";
  2254. }
  2255. Out << " }\n";
  2256. }
  2257. void CWriter::visitUnreachableInst(UnreachableInst &I) {
  2258. Out << " /*UNREACHABLE*/;\n";
  2259. }
  2260. bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
  2261. /// FIXME: This should be reenabled, but loop reordering safe!!
  2262. return true;
  2263. if (next(Function::iterator(From)) != Function::iterator(To))
  2264. return true; // Not the direct successor, we need a goto.
  2265. //isa<SwitchInst>(From->getTerminator())
  2266. if (LI->getLoopFor(From) != LI->getLoopFor(To))
  2267. return true;
  2268. return false;
  2269. }
  2270. void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
  2271. BasicBlock *Successor,
  2272. unsigned Indent) {
  2273. for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
  2274. PHINode *PN = cast<PHINode>(I);
  2275. // Now we have to do the printing.
  2276. Value *IV = PN->getIncomingValueForBlock(CurBlock);
  2277. if (!isa<UndefValue>(IV)) {
  2278. Out << std::string(Indent, ' ');
  2279. Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
  2280. writeOperand(IV);
  2281. Out << "; /* for PHI node */\n";
  2282. }
  2283. }
  2284. }
  2285. void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
  2286. unsigned Indent) {
  2287. if (isGotoCodeNecessary(CurBB, Succ)) {
  2288. Out << std::string(Indent, ' ') << " goto ";
  2289. writeOperand(Succ);
  2290. Out << ";\n";
  2291. }
  2292. }
  2293. // Branch instruction printing - Avoid printing out a branch to a basic block
  2294. // that immediately succeeds the current one.
  2295. //
  2296. void CWriter::visitBranchInst(BranchInst &I) {
  2297. if (I.isConditional()) {
  2298. if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
  2299. Out << " if (";
  2300. writeOperand(I.getCondition());
  2301. Out << ") {\n";
  2302. printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
  2303. printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
  2304. if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
  2305. Out << " } else {\n";
  2306. printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
  2307. printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
  2308. }
  2309. } else {
  2310. // First goto not necessary, assume second one is...
  2311. Out << " if (!";
  2312. writeOperand(I.getCondition());
  2313. Out << ") {\n";
  2314. printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
  2315. printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
  2316. }
  2317. Out << " }\n";
  2318. } else {
  2319. printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
  2320. printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
  2321. }
  2322. Out << "\n";
  2323. }
  2324. // PHI nodes get copied into temporary values at the end of predecessor basic
  2325. // blocks. We now need to copy these temporary values into the REAL value for
  2326. // the PHI.
  2327. void CWriter::visitPHINode(PHINode &I) {
  2328. writeOperand(&I);
  2329. Out << "__PHI_TEMPORARY";
  2330. }
  2331. void CWriter::visitBinaryOperator(Instruction &I) {
  2332. // binary instructions, shift instructions, setCond instructions.
  2333. assert(!isa<PointerType>(I.getType()));
  2334. // We must cast the results of binary operations which might be promoted.
  2335. bool needsCast = false;
  2336. if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
  2337. || (I.getType() == Type::FloatTy)) {
  2338. needsCast = true;
  2339. Out << "((";
  2340. printType(Out, I.getType(), false);
  2341. Out << ")(";
  2342. }
  2343. // If this is a negation operation, print it out as such. For FP, we don't
  2344. // want to print "-0.0 - X".
  2345. if (BinaryOperator::isNeg(&I)) {
  2346. Out << "-(";
  2347. writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
  2348. Out << ")";
  2349. } else if (BinaryOperator::isFNeg(&I)) {
  2350. Out << "-(";
  2351. writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
  2352. Out << ")";
  2353. } else if (I.getOpcode() == Instruction::FRem) {
  2354. // Output a call to fmod/fmodf instead of emitting a%b
  2355. if (I.getType() == Type::FloatTy)
  2356. Out << "fmodf(";
  2357. else if (I.getType() == Type::DoubleTy)
  2358. Out << "fmod(";
  2359. else // all 3 flavors of long double
  2360. Out << "fmodl(";
  2361. writeOperand(I.getOperand(0));
  2362. Out << ", ";
  2363. writeOperand(I.getOperand(1));
  2364. Out << ")";
  2365. } else {
  2366. // Write out the cast of the instruction's value back to the proper type
  2367. // if necessary.
  2368. bool NeedsClosingParens = writeInstructionCast(I);
  2369. // Certain instructions require the operand to be forced to a specific type
  2370. // so we use writeOperandWithCast here instead of writeOperand. Similarly
  2371. // below for operand 1
  2372. writeOperandWithCast(I.getOperand(0), I.getOpcode());
  2373. switch (I.getOpcode()) {
  2374. case Instruction::Add:
  2375. case Instruction::FAdd: Out << " + "; break;
  2376. case Instruction::Sub:
  2377. case Instruction::FSub: Out << " - "; break;
  2378. case Instruction::Mul:
  2379. case Instruction::FMul: Out << " * "; break;
  2380. case Instruction::URem:
  2381. case Instruction::SRem:
  2382. case Instruction::FRem: Out << " % "; break;
  2383. case Instruction::UDiv:
  2384. case Instruction::SDiv:
  2385. case Instruction::FDiv: Out << " / "; break;
  2386. case Instruction::And: Out << " & "; break;
  2387. case Instruction::Or: Out << " | "; break;
  2388. case Instruction::Xor: Out << " ^ "; break;
  2389. case Instruction::Shl : Out << " << "; break;
  2390. case Instruction::LShr:
  2391. case Instruction::AShr: Out << " >> "; break;
  2392. default: cerr << "Invalid operator type!" << I; abort();
  2393. }
  2394. writeOperandWithCast(I.getOperand(1), I.getOpcode());
  2395. if (NeedsClosingParens)
  2396. Out << "))";
  2397. }
  2398. if (needsCast) {
  2399. Out << "))";
  2400. }
  2401. }
  2402. void CWriter::visitICmpInst(ICmpInst &I) {
  2403. // We must cast the results of icmp which might be promoted.
  2404. bool needsCast = false;
  2405. // Write out the cast of the instruction's value back to the proper type
  2406. // if necessary.
  2407. bool NeedsClosingParens = writeInstructionCast(I);
  2408. // Certain icmp predicate require the operand to be forced to a specific type
  2409. // so we use writeOperandWithCast here instead of writeOperand. Similarly
  2410. // below for operand 1
  2411. writeOperandWithCast(I.getOperand(0), I);
  2412. switch (I.getPredicate()) {
  2413. case ICmpInst::ICMP_EQ: Out << " == "; break;
  2414. case ICmpInst::ICMP_NE: Out << " != "; break;
  2415. case ICmpInst::ICMP_ULE:
  2416. case ICmpInst::ICMP_SLE: Out << " <= "; break;
  2417. case ICmpInst::ICMP_UGE:
  2418. case ICmpInst::ICMP_SGE: Out << " >= "; break;
  2419. case ICmpInst::ICMP_ULT:
  2420. case ICmpInst::ICMP_SLT: Out << " < "; break;
  2421. case ICmpInst::ICMP_UGT:
  2422. case ICmpInst::ICMP_SGT: Out << " > "; break;
  2423. default: cerr << "Invalid icmp predicate!" << I; abort();
  2424. }
  2425. writeOperandWithCast(I.getOperand(1), I);
  2426. if (NeedsClosingParens)
  2427. Out << "))";
  2428. if (needsCast) {
  2429. Out << "))";
  2430. }
  2431. }
  2432. void CWriter::visitFCmpInst(FCmpInst &I) {
  2433. if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
  2434. Out << "0";
  2435. return;
  2436. }
  2437. if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
  2438. Out << "1";
  2439. return;
  2440. }
  2441. const char* op = 0;
  2442. switch (I.getPredicate()) {
  2443. default: assert(0 && "Illegal FCmp predicate");
  2444. case FCmpInst::FCMP_ORD: op = "ord"; break;
  2445. case FCmpInst::FCMP_UNO: op = "uno"; break;
  2446. case FCmpInst::FCMP_UEQ: op = "ueq"; break;
  2447. case FCmpInst::FCMP_UNE: op = "une"; break;
  2448. case FCmpInst::FCMP_ULT: op = "ult"; break;
  2449. case FCmpInst::FCMP_ULE: op = "ule"; break;
  2450. case FCmpInst::FCMP_UGT: op = "ugt"; break;
  2451. case FCmpInst::FCMP_UGE: op = "uge"; break;
  2452. case FCmpInst::FCMP_OEQ: op = "oeq"; break;
  2453. case FCmpInst::FCMP_ONE: op = "one"; break;
  2454. case FCmpInst::FCMP_OLT: op = "olt"; break;
  2455. case FCmpInst::FCMP_OLE: op = "ole"; break;
  2456. case FCmpInst::FCMP_OGT: op = "ogt"; break;
  2457. case FCmpInst::FCMP_OGE: op = "oge"; break;
  2458. }
  2459. Out << "llvm_fcmp_" << op << "(";
  2460. // Write the first operand
  2461. writeOperand(I.getOperand(0));
  2462. Out << ", ";
  2463. // Write the second operand
  2464. writeOperand(I.getOperand(1));
  2465. Out << ")";
  2466. }
  2467. static const char * getFloatBitCastField(const Type *Ty) {
  2468. switch (Ty->getTypeID()) {
  2469. default: assert(0 && "Invalid Type");
  2470. case Type::FloatTyID: return "Float";
  2471. case Type::DoubleTyID: return "Double";
  2472. case Type::IntegerTyID: {
  2473. unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
  2474. if (NumBits <= 32)
  2475. return "Int32";
  2476. else
  2477. return "Int64";
  2478. }
  2479. }
  2480. }
  2481. void CWriter::visitCastInst(CastInst &I) {
  2482. const Type *DstTy = I.getType();
  2483. const Type *SrcTy = I.getOperand(0)->getType();
  2484. if (isFPIntBitCast(I)) {
  2485. Out << '(';
  2486. // These int<->float and long<->double casts need to be handled specially
  2487. Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
  2488. << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
  2489. writeOperand(I.getOperand(0));
  2490. Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
  2491. << getFloatBitCastField(I.getType());
  2492. Out << ')';
  2493. return;
  2494. }
  2495. Out << '(';
  2496. printCast(I.getOpcode(), SrcTy, DstTy);
  2497. // Make a sext from i1 work by subtracting the i1 from 0 (an int).
  2498. if (SrcTy == Type::Int1Ty && I.getOpcode() == Instruction::SExt)
  2499. Out << "0-";
  2500. writeOperand(I.getOperand(0));
  2501. if (DstTy == Type::Int1Ty &&
  2502. (I.getOpcode() == Instruction::Trunc ||
  2503. I.getOpcode() == Instruction::FPToUI ||
  2504. I.getOpcode() == Instruction::FPToSI ||
  2505. I.getOpcode() == Instruction::PtrToInt)) {
  2506. // Make sure we really get a trunc to bool by anding the operand with 1
  2507. Out << "&1u";
  2508. }
  2509. Out << ')';
  2510. }
  2511. void CWriter::visitSelectInst(SelectInst &I) {
  2512. Out << "((";
  2513. writeOperand(I.getCondition());
  2514. Out << ") ? (";
  2515. writeOperand(I.getTrueValue());
  2516. Out << ") : (";
  2517. writeOperand(I.getFalseValue());
  2518. Out << "))";
  2519. }
  2520. void CWriter::lowerIntrinsics(Function &F) {
  2521. // This is used to keep track of intrinsics that get generated to a lowered
  2522. // function. We must generate the prototypes before the function body which
  2523. // will only be expanded on first use (by the loop below).
  2524. std::vector<Function*> prototypesToGen;
  2525. // Examine all the instructions in this function to find the intrinsics that
  2526. // need to be lowered.
  2527. for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
  2528. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
  2529. if (CallInst *CI = dyn_cast<CallInst>(I++))
  2530. if (Function *F = CI->getCalledFunction())
  2531. switch (F->getIntrinsicID()) {
  2532. case Intrinsic::not_intrinsic:
  2533. case Intrinsic::memory_barrier:
  2534. case Intrinsic::vastart:
  2535. case Intrinsic::vacopy:
  2536. case Intrinsic::vaend:
  2537. case Intrinsic::returnaddress:
  2538. case Intrinsic::frameaddress:
  2539. case Intrinsic::setjmp:
  2540. case Intrinsic::longjmp:
  2541. case Intrinsic::prefetch:
  2542. case Intrinsic::dbg_stoppoint:
  2543. case Intrinsic::powi:
  2544. case Intrinsic::x86_sse_cmp_ss:
  2545. case Intrinsic::x86_sse_cmp_ps:
  2546. case Intrinsic::x86_sse2_cmp_sd:
  2547. case Intrinsic::x86_sse2_cmp_pd:
  2548. case Intrinsic::ppc_altivec_lvsl:
  2549. // We directly implement these intrinsics
  2550. break;
  2551. default:
  2552. // If this is an intrinsic that directly corresponds to a GCC
  2553. // builtin, we handle it.
  2554. const char *BuiltinName = "";
  2555. #define GET_GCC_BUILTIN_NAME
  2556. #include "llvm/Intrinsics.gen"
  2557. #undef GET_GCC_BUILTIN_NAME
  2558. // If we handle it, don't lower it.
  2559. if (BuiltinName[0]) break;
  2560. // All other intrinsic calls we must lower.
  2561. Instruction *Before = 0;
  2562. if (CI != &BB->front())
  2563. Before = prior(BasicBlock::iterator(CI));
  2564. IL->LowerIntrinsicCall(CI);
  2565. if (Before) { // Move iterator to instruction after call
  2566. I = Before; ++I;
  2567. } else {
  2568. I = BB->begin();
  2569. }
  2570. // If the intrinsic got lowered to another call, and that call has
  2571. // a definition then we need to make sure its prototype is emitted
  2572. // before any calls to it.
  2573. if (CallInst *Call = dyn_cast<CallInst>(I))
  2574. if (Function *NewF = Call->getCalledFunction())
  2575. if (!NewF->isDeclaration())
  2576. prototypesToGen.push_back(NewF);
  2577. break;
  2578. }
  2579. // We may have collected some prototypes to emit in the loop above.
  2580. // Emit them now, before the function that uses them is emitted. But,
  2581. // be careful not to emit them twice.
  2582. std::vector<Function*>::iterator I = prototypesToGen.begin();
  2583. std::vector<Function*>::iterator E = prototypesToGen.end();
  2584. for ( ; I != E; ++I) {
  2585. if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
  2586. Out << '\n';
  2587. printFunctionSignature(*I, true);
  2588. Out << ";\n";
  2589. }
  2590. }
  2591. }
  2592. void CWriter::visitCallInst(CallInst &I) {
  2593. if (isa<InlineAsm>(I.getOperand(0)))
  2594. return visitInlineAsm(I);
  2595. bool WroteCallee = false;
  2596. // Handle intrinsic function calls first...
  2597. if (Function *F = I.getCalledFunction())
  2598. if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
  2599. if (visitBuiltinCall(I, ID, WroteCallee))
  2600. return;
  2601. Value *Callee = I.getCalledValue();
  2602. const PointerType *PTy = cast<PointerType>(Callee->getType());
  2603. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  2604. // If this is a call to a struct-return function, assign to the first
  2605. // parameter instead of passing it to the call.
  2606. const AttrListPtr &PAL = I.getAttributes();
  2607. bool hasByVal = I.hasByValArgument();
  2608. bool isStructRet = I.hasStructRetAttr();
  2609. if (isStructRet) {
  2610. writeOperandDeref(I.getOperand(1));
  2611. Out << " = ";
  2612. }
  2613. if (I.isTailCall()) Out << " /*tail*/ ";
  2614. if (!WroteCallee) {
  2615. // If this is an indirect call to a struct return function, we need to cast
  2616. // the pointer. Ditto for indirect calls with byval arguments.
  2617. bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
  2618. // GCC is a real PITA. It does not permit codegening casts of functions to
  2619. // function pointers if they are in a call (it generates a trap instruction
  2620. // instead!). We work around this by inserting a cast to void* in between
  2621. // the function and the function pointer cast. Unfortunately, we can't just
  2622. // form the constant expression here, because the folder will immediately
  2623. // nuke it.
  2624. //
  2625. // Note finally, that this is completely unsafe. ANSI C does not guarantee
  2626. // that void* and function pointers have the same size. :( To deal with this
  2627. // in the common case, we handle casts where the number of arguments passed
  2628. // match exactly.
  2629. //
  2630. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
  2631. if (CE->isCast())
  2632. if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
  2633. NeedsCast = true;
  2634. Callee = RF;
  2635. }
  2636. if (NeedsCast) {
  2637. // Ok, just cast the pointer type.
  2638. Out << "((";
  2639. if (isStructRet)
  2640. printStructReturnPointerFunctionType(Out, PAL,
  2641. cast<PointerType>(I.getCalledValue()->getType()));
  2642. else if (hasByVal)
  2643. printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
  2644. else
  2645. printType(Out, I.getCalledValue()->getType());
  2646. Out << ")(void*)";
  2647. }
  2648. writeOperand(Callee);
  2649. if (NeedsCast) Out << ')';
  2650. }
  2651. Out << '(';
  2652. unsigned NumDeclaredParams = FTy->getNumParams();
  2653. CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
  2654. unsigned ArgNo = 0;
  2655. if (isStructRet) { // Skip struct return argument.
  2656. ++AI;
  2657. ++ArgNo;
  2658. }
  2659. bool PrintedArg = false;
  2660. for (; AI != AE; ++AI, ++ArgNo) {
  2661. if (PrintedArg) Out << ", ";
  2662. if (ArgNo < NumDeclaredParams &&
  2663. (*AI)->getType() != FTy->getParamType(ArgNo)) {
  2664. Out << '(';
  2665. printType(Out, FTy->getParamType(ArgNo),
  2666. /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
  2667. Out << ')';
  2668. }
  2669. // Check if the argument is expected to be passed by value.
  2670. if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
  2671. writeOperandDeref(*AI);
  2672. else
  2673. writeOperand(*AI);
  2674. PrintedArg = true;
  2675. }
  2676. Out << ')';
  2677. }
  2678. /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
  2679. /// if the entire call is handled, return false it it wasn't handled, and
  2680. /// optionally set 'WroteCallee' if the callee has already been printed out.
  2681. bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
  2682. bool &WroteCallee) {
  2683. switch (ID) {
  2684. default: {
  2685. // If this is an intrinsic that directly corresponds to a GCC
  2686. // builtin, we emit it here.
  2687. const char *BuiltinName = "";
  2688. Function *F = I.getCalledFunction();
  2689. #define GET_GCC_BUILTIN_NAME
  2690. #include "llvm/Intrinsics.gen"
  2691. #undef GET_GCC_BUILTIN_NAME
  2692. assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
  2693. Out << BuiltinName;
  2694. WroteCallee = true;
  2695. return false;
  2696. }
  2697. case Intrinsic::memory_barrier:
  2698. Out << "__sync_synchronize()";
  2699. return true;
  2700. case Intrinsic::vastart:
  2701. Out << "0; ";
  2702. Out << "va_start(*(va_list*)";
  2703. writeOperand(I.getOperand(1));
  2704. Out << ", ";
  2705. // Output the last argument to the enclosing function.
  2706. if (I.getParent()->getParent()->arg_empty()) {
  2707. cerr << "The C backend does not currently support zero "
  2708. << "argument varargs functions, such as '"
  2709. << I.getParent()->getParent()->getName() << "'!\n";
  2710. abort();
  2711. }
  2712. writeOperand(--I.getParent()->getParent()->arg_end());
  2713. Out << ')';
  2714. return true;
  2715. case Intrinsic::vaend:
  2716. if (!isa<ConstantPointerNull>(I.getOperand(1))) {
  2717. Out << "0; va_end(*(va_list*)";
  2718. writeOperand(I.getOperand(1));
  2719. Out << ')';
  2720. } else {
  2721. Out << "va_end(*(va_list*)0)";
  2722. }
  2723. return true;
  2724. case Intrinsic::vacopy:
  2725. Out << "0; ";
  2726. Out << "va_copy(*(va_list*)";
  2727. writeOperand(I.getOperand(1));
  2728. Out << ", *(va_list*)";
  2729. writeOperand(I.getOperand(2));
  2730. Out << ')';
  2731. return true;
  2732. case Intrinsic::returnaddress:
  2733. Out << "__builtin_return_address(";
  2734. writeOperand(I.getOperand(1));
  2735. Out << ')';
  2736. return true;
  2737. case Intrinsic::frameaddress:
  2738. Out << "__builtin_frame_address(";
  2739. writeOperand(I.getOperand(1));
  2740. Out << ')';
  2741. return true;
  2742. case Intrinsic::powi:
  2743. Out << "__builtin_powi(";
  2744. writeOperand(I.getOperand(1));
  2745. Out << ", ";
  2746. writeOperand(I.getOperand(2));
  2747. Out << ')';
  2748. return true;
  2749. case Intrinsic::setjmp:
  2750. Out << "setjmp(*(jmp_buf*)";
  2751. writeOperand(I.getOperand(1));
  2752. Out << ')';
  2753. return true;
  2754. case Intrinsic::longjmp:
  2755. Out << "longjmp(*(jmp_buf*)";
  2756. writeOperand(I.getOperand(1));
  2757. Out << ", ";
  2758. writeOperand(I.getOperand(2));
  2759. Out << ')';
  2760. return true;
  2761. case Intrinsic::prefetch:
  2762. Out << "LLVM_PREFETCH((const void *)";
  2763. writeOperand(I.getOperand(1));
  2764. Out << ", ";
  2765. writeOperand(I.getOperand(2));
  2766. Out << ", ";
  2767. writeOperand(I.getOperand(3));
  2768. Out << ")";
  2769. return true;
  2770. case Intrinsic::stacksave:
  2771. // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
  2772. // to work around GCC bugs (see PR1809).
  2773. Out << "0; *((void**)&" << GetValueName(&I)
  2774. << ") = __builtin_stack_save()";
  2775. return true;
  2776. case Intrinsic::dbg_stoppoint: {
  2777. // If we use writeOperand directly we get a "u" suffix which is rejected
  2778. // by gcc.
  2779. std::stringstream SPIStr;
  2780. DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
  2781. SPI.getDirectory()->print(SPIStr);
  2782. Out << "\n#line "
  2783. << SPI.getLine()
  2784. << " \"";
  2785. Out << SPIStr.str();
  2786. SPIStr.clear();
  2787. SPI.getFileName()->print(SPIStr);
  2788. Out << SPIStr.str() << "\"\n";
  2789. return true;
  2790. }
  2791. case Intrinsic::x86_sse_cmp_ss:
  2792. case Intrinsic::x86_sse_cmp_ps:
  2793. case Intrinsic::x86_sse2_cmp_sd:
  2794. case Intrinsic::x86_sse2_cmp_pd:
  2795. Out << '(';
  2796. printType(Out, I.getType());
  2797. Out << ')';
  2798. // Multiple GCC builtins multiplex onto this intrinsic.
  2799. switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
  2800. default: assert(0 && "Invalid llvm.x86.sse.cmp!");
  2801. case 0: Out << "__builtin_ia32_cmpeq"; break;
  2802. case 1: Out << "__builtin_ia32_cmplt"; break;
  2803. case 2: Out << "__builtin_ia32_cmple"; break;
  2804. case 3: Out << "__builtin_ia32_cmpunord"; break;
  2805. case 4: Out << "__builtin_ia32_cmpneq"; break;
  2806. case 5: Out << "__builtin_ia32_cmpnlt"; break;
  2807. case 6: Out << "__builtin_ia32_cmpnle"; break;
  2808. case 7: Out << "__builtin_ia32_cmpord"; break;
  2809. }
  2810. if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
  2811. Out << 'p';
  2812. else
  2813. Out << 's';
  2814. if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
  2815. Out << 's';
  2816. else
  2817. Out << 'd';
  2818. Out << "(";
  2819. writeOperand(I.getOperand(1));
  2820. Out << ", ";
  2821. writeOperand(I.getOperand(2));
  2822. Out << ")";
  2823. return true;
  2824. case Intrinsic::ppc_altivec_lvsl:
  2825. Out << '(';
  2826. printType(Out, I.getType());
  2827. Out << ')';
  2828. Out << "__builtin_altivec_lvsl(0, (void*)";
  2829. writeOperand(I.getOperand(1));
  2830. Out << ")";
  2831. return true;
  2832. }
  2833. }
  2834. //This converts the llvm constraint string to something gcc is expecting.
  2835. //TODO: work out platform independent constraints and factor those out
  2836. // of the per target tables
  2837. // handle multiple constraint codes
  2838. std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
  2839. assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
  2840. const char *const *table = 0;
  2841. //Grab the translation table from TargetAsmInfo if it exists
  2842. if (!TAsm) {
  2843. std::string E;
  2844. const TargetMachineRegistry::entry* Match =
  2845. TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
  2846. if (Match) {
  2847. //Per platform Target Machines don't exist, so create it
  2848. // this must be done only once
  2849. const TargetMachine* TM = Match->CtorFn(*TheModule, "");
  2850. TAsm = TM->getTargetAsmInfo();
  2851. }
  2852. }
  2853. if (TAsm)
  2854. table = TAsm->getAsmCBE();
  2855. //Search the translation table if it exists
  2856. for (int i = 0; table && table[i]; i += 2)
  2857. if (c.Codes[0] == table[i])
  2858. return table[i+1];
  2859. //default is identity
  2860. return c.Codes[0];
  2861. }
  2862. //TODO: import logic from AsmPrinter.cpp
  2863. static std::string gccifyAsm(std::string asmstr) {
  2864. for (std::string::size_type i = 0; i != asmstr.size(); ++i)
  2865. if (asmstr[i] == '\n')
  2866. asmstr.replace(i, 1, "\\n");
  2867. else if (asmstr[i] == '\t')
  2868. asmstr.replace(i, 1, "\\t");
  2869. else if (asmstr[i] == '$') {
  2870. if (asmstr[i + 1] == '{') {
  2871. std::string::size_type a = asmstr.find_first_of(':', i + 1);
  2872. std::string::size_type b = asmstr.find_first_of('}', i + 1);
  2873. std::string n = "%" +
  2874. asmstr.substr(a + 1, b - a - 1) +
  2875. asmstr.substr(i + 2, a - i - 2);
  2876. asmstr.replace(i, b - i + 1, n);
  2877. i += n.size() - 1;
  2878. } else
  2879. asmstr.replace(i, 1, "%");
  2880. }
  2881. else if (asmstr[i] == '%')//grr
  2882. { asmstr.replace(i, 1, "%%"); ++i;}
  2883. return asmstr;
  2884. }
  2885. //TODO: assumptions about what consume arguments from the call are likely wrong
  2886. // handle communitivity
  2887. void CWriter::visitInlineAsm(CallInst &CI) {
  2888. InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
  2889. std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
  2890. std::vector<std::pair<Value*, int> > ResultVals;
  2891. if (CI.getType() == Type::VoidTy)
  2892. ;
  2893. else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
  2894. for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
  2895. ResultVals.push_back(std::make_pair(&CI, (int)i));
  2896. } else {
  2897. ResultVals.push_back(std::make_pair(&CI, -1));
  2898. }
  2899. // Fix up the asm string for gcc and emit it.
  2900. Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
  2901. Out << " :";
  2902. unsigned ValueCount = 0;
  2903. bool IsFirst = true;
  2904. // Convert over all the output constraints.
  2905. for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
  2906. E = Constraints.end(); I != E; ++I) {
  2907. if (I->Type != InlineAsm::isOutput) {
  2908. ++ValueCount;
  2909. continue; // Ignore non-output constraints.
  2910. }
  2911. assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
  2912. std::string C = InterpretASMConstraint(*I);
  2913. if (C.empty()) continue;
  2914. if (!IsFirst) {
  2915. Out << ", ";
  2916. IsFirst = false;
  2917. }
  2918. // Unpack the dest.
  2919. Value *DestVal;
  2920. int DestValNo = -1;
  2921. if (ValueCount < ResultVals.size()) {
  2922. DestVal = ResultVals[ValueCount].first;
  2923. DestValNo = ResultVals[ValueCount].second;
  2924. } else
  2925. DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
  2926. if (I->isEarlyClobber)
  2927. C = "&"+C;
  2928. Out << "\"=" << C << "\"(" << GetValueName(DestVal);
  2929. if (DestValNo != -1)
  2930. Out << ".field" << DestValNo; // Multiple retvals.
  2931. Out << ")";
  2932. ++ValueCount;
  2933. }
  2934. // Convert over all the input constraints.
  2935. Out << "\n :";
  2936. IsFirst = true;
  2937. ValueCount = 0;
  2938. for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
  2939. E = Constraints.end(); I != E; ++I) {
  2940. if (I->Type != InlineAsm::isInput) {
  2941. ++ValueCount;
  2942. continue; // Ignore non-input constraints.
  2943. }
  2944. assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
  2945. std::string C = InterpretASMConstraint(*I);
  2946. if (C.empty()) continue;
  2947. if (!IsFirst) {
  2948. Out << ", ";
  2949. IsFirst = false;
  2950. }
  2951. assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
  2952. Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
  2953. Out << "\"" << C << "\"(";
  2954. if (!I->isIndirect)
  2955. writeOperand(SrcVal);
  2956. else
  2957. writeOperandDeref(SrcVal);
  2958. Out << ")";
  2959. }
  2960. // Convert over the clobber constraints.
  2961. IsFirst = true;
  2962. ValueCount = 0;
  2963. for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
  2964. E = Constraints.end(); I != E; ++I) {
  2965. if (I->Type != InlineAsm::isClobber)
  2966. continue; // Ignore non-input constraints.
  2967. assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
  2968. std::string C = InterpretASMConstraint(*I);
  2969. if (C.empty()) continue;
  2970. if (!IsFirst) {
  2971. Out << ", ";
  2972. IsFirst = false;
  2973. }
  2974. Out << '\"' << C << '"';
  2975. }
  2976. Out << ")";
  2977. }
  2978. void CWriter::visitMallocInst(MallocInst &I) {
  2979. assert(0 && "lowerallocations pass didn't work!");
  2980. }
  2981. void CWriter::visitAllocaInst(AllocaInst &I) {
  2982. Out << '(';
  2983. printType(Out, I.getType());
  2984. Out << ") alloca(sizeof(";
  2985. printType(Out, I.getType()->getElementType());
  2986. Out << ')';
  2987. if (I.isArrayAllocation()) {
  2988. Out << " * " ;
  2989. writeOperand(I.getOperand(0));
  2990. }
  2991. Out << ')';
  2992. }
  2993. void CWriter::visitFreeInst(FreeInst &I) {
  2994. assert(0 && "lowerallocations pass didn't work!");
  2995. }
  2996. void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
  2997. gep_type_iterator E, bool Static) {
  2998. // If there are no indices, just print out the pointer.
  2999. if (I == E) {
  3000. writeOperand(Ptr);
  3001. return;
  3002. }
  3003. // Find out if the last index is into a vector. If so, we have to print this
  3004. // specially. Since vectors can't have elements of indexable type, only the
  3005. // last index could possibly be of a vector element.
  3006. const VectorType *LastIndexIsVector = 0;
  3007. {
  3008. for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
  3009. LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
  3010. }
  3011. Out << "(";
  3012. // If the last index is into a vector, we can't print it as &a[i][j] because
  3013. // we can't index into a vector with j in GCC. Instead, emit this as
  3014. // (((float*)&a[i])+j)
  3015. if (LastIndexIsVector) {
  3016. Out << "((";
  3017. printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
  3018. Out << ")(";
  3019. }
  3020. Out << '&';
  3021. // If the first index is 0 (very typical) we can do a number of
  3022. // simplifications to clean up the code.
  3023. Value *FirstOp = I.getOperand();
  3024. if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
  3025. // First index isn't simple, print it the hard way.
  3026. writeOperand(Ptr);
  3027. } else {
  3028. ++I; // Skip the zero index.
  3029. // Okay, emit the first operand. If Ptr is something that is already address
  3030. // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
  3031. if (isAddressExposed(Ptr)) {
  3032. writeOperandInternal(Ptr, Static);
  3033. } else if (I != E && isa<StructType>(*I)) {
  3034. // If we didn't already emit the first operand, see if we can print it as
  3035. // P->f instead of "P[0].f"
  3036. writeOperand(Ptr);
  3037. Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
  3038. ++I; // eat the struct index as well.
  3039. } else {
  3040. // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
  3041. Out << "(*";
  3042. writeOperand(Ptr);
  3043. Out << ")";
  3044. }
  3045. }
  3046. for (; I != E; ++I) {
  3047. if (isa<StructType>(*I)) {
  3048. Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
  3049. } else if (isa<ArrayType>(*I)) {
  3050. Out << ".array[";
  3051. writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
  3052. Out << ']';
  3053. } else if (!isa<VectorType>(*I)) {
  3054. Out << '[';
  3055. writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
  3056. Out << ']';
  3057. } else {
  3058. // If the last index is into a vector, then print it out as "+j)". This
  3059. // works with the 'LastIndexIsVector' code above.
  3060. if (isa<Constant>(I.getOperand()) &&
  3061. cast<Constant>(I.getOperand())->isNullValue()) {
  3062. Out << "))"; // avoid "+0".
  3063. } else {
  3064. Out << ")+(";
  3065. writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
  3066. Out << "))";
  3067. }
  3068. }
  3069. }
  3070. Out << ")";
  3071. }
  3072. void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
  3073. bool IsVolatile, unsigned Alignment) {
  3074. bool IsUnaligned = Alignment &&
  3075. Alignment < TD->getABITypeAlignment(OperandType);
  3076. if (!IsUnaligned)
  3077. Out << '*';
  3078. if (IsVolatile || IsUnaligned) {
  3079. Out << "((";
  3080. if (IsUnaligned)
  3081. Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
  3082. printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
  3083. if (IsUnaligned) {
  3084. Out << "; } ";
  3085. if (IsVolatile) Out << "volatile ";
  3086. Out << "*";
  3087. }
  3088. Out << ")";
  3089. }
  3090. writeOperand(Operand);
  3091. if (IsVolatile || IsUnaligned) {
  3092. Out << ')';
  3093. if (IsUnaligned)
  3094. Out << "->data";
  3095. }
  3096. }
  3097. void CWriter::visitLoadInst(LoadInst &I) {
  3098. writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
  3099. I.getAlignment());
  3100. }
  3101. void CWriter::visitStoreInst(StoreInst &I) {
  3102. writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
  3103. I.isVolatile(), I.getAlignment());
  3104. Out << " = ";
  3105. Value *Operand = I.getOperand(0);
  3106. Constant *BitMask = 0;
  3107. if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
  3108. if (!ITy->isPowerOf2ByteWidth())
  3109. // We have a bit width that doesn't match an even power-of-2 byte
  3110. // size. Consequently we must & the value with the type's bit mask
  3111. BitMask = ConstantInt::get(ITy, ITy->getBitMask());
  3112. if (BitMask)
  3113. Out << "((";
  3114. writeOperand(Operand);
  3115. if (BitMask) {
  3116. Out << ") & ";
  3117. printConstant(BitMask, false);
  3118. Out << ")";
  3119. }
  3120. }
  3121. void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
  3122. printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
  3123. gep_type_end(I), false);
  3124. }
  3125. void CWriter::visitVAArgInst(VAArgInst &I) {
  3126. Out << "va_arg(*(va_list*)";
  3127. writeOperand(I.getOperand(0));
  3128. Out << ", ";
  3129. printType(Out, I.getType());
  3130. Out << ");\n ";
  3131. }
  3132. void CWriter::visitInsertElementInst(InsertElementInst &I) {
  3133. const Type *EltTy = I.getType()->getElementType();
  3134. writeOperand(I.getOperand(0));
  3135. Out << ";\n ";
  3136. Out << "((";
  3137. printType(Out, PointerType::getUnqual(EltTy));
  3138. Out << ")(&" << GetValueName(&I) << "))[";
  3139. writeOperand(I.getOperand(2));
  3140. Out << "] = (";
  3141. writeOperand(I.getOperand(1));
  3142. Out << ")";
  3143. }
  3144. void CWriter::visitExtractElementInst(ExtractElementInst &I) {
  3145. // We know that our operand is not inlined.
  3146. Out << "((";
  3147. const Type *EltTy =
  3148. cast<VectorType>(I.getOperand(0)->getType())->getElementType();
  3149. printType(Out, PointerType::getUnqual(EltTy));
  3150. Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
  3151. writeOperand(I.getOperand(1));
  3152. Out << "]";
  3153. }
  3154. void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
  3155. Out << "(";
  3156. printType(Out, SVI.getType());
  3157. Out << "){ ";
  3158. const VectorType *VT = SVI.getType();
  3159. unsigned NumElts = VT->getNumElements();
  3160. const Type *EltTy = VT->getElementType();
  3161. for (unsigned i = 0; i != NumElts; ++i) {
  3162. if (i) Out << ", ";
  3163. int SrcVal = SVI.getMaskValue(i);
  3164. if ((unsigned)SrcVal >= NumElts*2) {
  3165. Out << " 0/*undef*/ ";
  3166. } else {
  3167. Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
  3168. if (isa<Instruction>(Op)) {
  3169. // Do an extractelement of this value from the appropriate input.
  3170. Out << "((";
  3171. printType(Out, PointerType::getUnqual(EltTy));
  3172. Out << ")(&" << GetValueName(Op)
  3173. << "))[" << (SrcVal & (NumElts-1)) << "]";
  3174. } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
  3175. Out << "0";
  3176. } else {
  3177. printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
  3178. (NumElts-1)),
  3179. false);
  3180. }
  3181. }
  3182. }
  3183. Out << "}";
  3184. }
  3185. void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
  3186. // Start by copying the entire aggregate value into the result variable.
  3187. writeOperand(IVI.getOperand(0));
  3188. Out << ";\n ";
  3189. // Then do the insert to update the field.
  3190. Out << GetValueName(&IVI);
  3191. for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
  3192. i != e; ++i) {
  3193. const Type *IndexedTy =
  3194. ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
  3195. if (isa<ArrayType>(IndexedTy))
  3196. Out << ".array[" << *i << "]";
  3197. else
  3198. Out << ".field" << *i;
  3199. }
  3200. Out << " = ";
  3201. writeOperand(IVI.getOperand(1));
  3202. }
  3203. void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
  3204. Out << "(";
  3205. if (isa<UndefValue>(EVI.getOperand(0))) {
  3206. Out << "(";
  3207. printType(Out, EVI.getType());
  3208. Out << ") 0/*UNDEF*/";
  3209. } else {
  3210. Out << GetValueName(EVI.getOperand(0));
  3211. for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
  3212. i != e; ++i) {
  3213. const Type *IndexedTy =
  3214. ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
  3215. if (isa<ArrayType>(IndexedTy))
  3216. Out << ".array[" << *i << "]";
  3217. else
  3218. Out << ".field" << *i;
  3219. }
  3220. }
  3221. Out << ")";
  3222. }
  3223. //===----------------------------------------------------------------------===//
  3224. // External Interface declaration
  3225. //===----------------------------------------------------------------------===//
  3226. bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
  3227. raw_ostream &o,
  3228. CodeGenFileType FileType,
  3229. CodeGenOpt::Level OptLevel) {
  3230. if (FileType != TargetMachine::AssemblyFile) return true;
  3231. PM.add(createGCLoweringPass());
  3232. PM.add(createLowerAllocationsPass(true));
  3233. PM.add(createLowerInvokePass());
  3234. PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
  3235. PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
  3236. PM.add(new CWriter(o));
  3237. PM.add(createGCInfoDeleter());
  3238. return false;
  3239. }