forked from ispc/ispc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cbackend.cpp
5009 lines (4455 loc) · 174 KB
/
cbackend.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This library converts LLVM code to C code, compilable by GCC and other C
// compilers.
//
//===----------------------------------------------------------------------===//
#include "ispc.h"
#include "module.h"
#include <stdio.h>
#ifndef _MSC_VER
#include <inttypes.h>
#define HAVE_PRINTF_A 1
#define ENABLE_CBE_PRINTF_A 1
#endif
#ifndef PRIx64
#define PRIx64 "llx"
#endif
#include "llvmutil.h"
#if defined(LLVM_3_2)
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/CallingConv.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/InlineAsm.h"
#else
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/InlineAsm.h"
#endif
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
#if defined(LLVM_3_2)
#include "llvm/TypeFinder.h"
#else // LLVM_3_3 +
#include "llvm/IR/TypeFinder.h"
#endif
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/ConstantsScanner.h"
#if defined(LLVM_3_2) || defined(LLVM_3_3) || defined(LLVM_3_4) || defined(LLVM_3_5)
#include "llvm/Analysis/FindUsedTypes.h"
#endif
#include "llvm/Analysis/LoopInfo.h"
#if !defined(LLVM_3_2) && !defined(LLVM_3_3) && !defined(LLVM_3_4)
#include "llvm/IR/Verifier.h"
#include <llvm/IR/IRPrintingPasses.h>
#include "llvm/IR/CallSite.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/Support/FileSystem.h"
#else
#include "llvm/Analysis/Verifier.h"
#include <llvm/Assembly/PrintModulePass.h>
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#endif
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
//#include "llvm/Target/Mangler.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#if defined(LLVM_3_2)
#include "llvm/DataLayout.h"
#else // LLVM 3.3+
#include "llvm/IR/DataLayout.h"
#endif
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
#if defined(LLVM_3_2)
#include "llvm/Support/InstVisitor.h"
#elif defined (LLVM_3_3) || defined (LLVM_3_4)
#include "llvm/InstVisitor.h"
#else // LLVM 3.5+
#include "llvm/IR/InstVisitor.h"
#endif
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/Host.h"
#include "llvm/Target/TargetMachine.h"
#if defined(LLVM_3_2) || defined(LLVM_3_3) || defined(LLVM_3_4)
#include "llvm/Config/config.h"
#endif
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Support/ToolOutputFile.h>
#include <algorithm>
// Some ms header decided to define setjmp as _setjmp, undo this for this file.
#ifdef _MSC_VER
#undef setjmp
#define snprintf _snprintf
#endif
// FIXME:
namespace {
/// TypeFinder - Walk over a module, identifying all of the types that are
/// used by the module.
class TypeFinder {
// To avoid walking constant expressions multiple times and other IR
// objects, we keep several helper maps.
llvm::DenseSet<const llvm::Value*> VisitedConstants;
llvm::DenseSet<llvm::Type*> VisitedTypes;
std::vector<llvm::ArrayType*> &ArrayTypes;
public:
TypeFinder(std::vector<llvm::ArrayType*> &t)
: ArrayTypes(t) {}
void run(const llvm::Module &M) {
// Get types from global variables.
for (llvm::Module::const_global_iterator I = M.global_begin(),
E = M.global_end(); I != E; ++I) {
incorporateType(I->getType());
if (I->hasInitializer())
incorporateValue(I->getInitializer());
}
// Get types from aliases.
for (llvm::Module::const_alias_iterator I = M.alias_begin(),
E = M.alias_end(); I != E; ++I) {
incorporateType(I->getType());
if (const llvm::Value *Aliasee = I->getAliasee())
incorporateValue(Aliasee);
}
llvm::SmallVector<std::pair<unsigned, llvm::MDNode*>, 4> MDForInst;
// Get types from functions.
for (llvm::Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
incorporateType(FI->getType());
for (llvm::Function::const_iterator BB = FI->begin(), E = FI->end();
BB != E;++BB)
for (llvm::BasicBlock::const_iterator II = BB->begin(),
E = BB->end(); II != E; ++II) {
const llvm::Instruction &I = *II;
// Operands of SwitchInsts changed format after 3.1
// Seems like there ought to be better way to do what we
// want here. For now, punt on SwitchInsts.
if (llvm::isa<llvm::SwitchInst>(&I)) continue;
// Incorporate the type of the instruction and all its operands.
incorporateType(I.getType());
for (llvm::User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
OI != OE; ++OI)
incorporateValue(*OI);
// Incorporate types hiding in metadata.
I.getAllMetadataOtherThanDebugLoc(MDForInst);
for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
#if defined(LLVM_3_2) || defined(LLVM_3_3) || defined(LLVM_3_4) || defined(LLVM_3_5)
incorporateMDNode(MDForInst[i].second);
#else // LLVM 3.6+
incorporateMDNode(llvm::cast<llvm::MDNode>(MDForInst[i].second));
#endif
MDForInst.clear();
}
}
for (llvm::Module::const_named_metadata_iterator I = M.named_metadata_begin(),
E = M.named_metadata_end(); I != E; ++I) {
const llvm::NamedMDNode *NMD = I;
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
#if defined(LLVM_3_2) || defined(LLVM_3_3) || defined(LLVM_3_4) || defined(LLVM_3_5)
incorporateMDNode(NMD->getOperand(i));
#else // LLVM 3.6+
incorporateMDNode(llvm::cast<llvm::MDNode>(NMD->getOperand(i)));
#endif
}
}
private:
void incorporateType(llvm::Type *Ty) {
// Check to see if we're already visited this type.
if (!VisitedTypes.insert(Ty).second)
return;
if (llvm::ArrayType *ATy = llvm::dyn_cast<llvm::ArrayType>(Ty))
ArrayTypes.push_back(ATy);
// Recursively walk all contained types.
for (llvm::Type::subtype_iterator I = Ty->subtype_begin(),
E = Ty->subtype_end(); I != E; ++I)
incorporateType(*I);
}
/// incorporateValue - This method is used to walk operand lists finding
/// types hiding in constant expressions and other operands that won't be
/// walked in other ways. GlobalValues, basic blocks, instructions, and
/// inst operands are all explicitly enumerated.
void incorporateValue(const llvm::Value *V) {
if (const llvm::MDNode *M = llvm::dyn_cast<llvm::MDNode>(V))
return incorporateMDNode(M);
if (!llvm::isa<llvm::Constant>(V) || llvm::isa<llvm::GlobalValue>(V)) return;
// Already visited?
if (!VisitedConstants.insert(V).second)
return;
// Check this type.
incorporateType(V->getType());
// Look in operands for types.
const llvm::User *U = llvm::cast<llvm::User>(V);
for (llvm::Constant::const_op_iterator I = U->op_begin(),
E = U->op_end(); I != E;++I)
incorporateValue(*I);
}
void incorporateMDNode(const llvm::MDNode *V) {
// Already visited?
if (!VisitedConstants.insert(V).second)
return;
// Look in operands for types.
for (unsigned i = 0, e = V->getNumOperands(); i != e; ++i)
if (llvm::Value *Op = V->getOperand(i))
incorporateValue(Op);
}
};
} // end anonymous namespace
static void findUsedArrayTypes(const llvm::Module *m, std::vector<llvm::ArrayType*> &t) {
TypeFinder(t).run(*m);
}
namespace {
class CBEMCAsmInfo : public llvm::MCAsmInfo {
public:
CBEMCAsmInfo() {
#if defined(LLVM_3_2) || defined(LLVM_3_3) || defined(LLVM_3_4)
GlobalPrefix = "";
#endif
PrivateGlobalPrefix = "";
}
};
/// CWriter - This class is the main chunk of code that converts an LLVM
/// module to a C translation unit.
class CWriter : public llvm::FunctionPass, public llvm::InstVisitor<CWriter> {
llvm::formatted_raw_ostream &Out;
llvm::IntrinsicLowering *IL;
//llvm::Mangler *Mang;
llvm::LoopInfo *LI;
const llvm::Module *TheModule;
const llvm::MCAsmInfo* TAsm;
const llvm::MCRegisterInfo *MRI;
const llvm::MCObjectFileInfo *MOFI;
llvm::MCContext *TCtx;
// FIXME: it's ugly to have the name be "TD" here, but it saves us
// lots of ifdefs in the below since the new DataLayout and the old
// TargetData have generally similar interfaces...
const llvm::DataLayout* TD;
std::map<const llvm::ConstantFP *, unsigned> FPConstantMap;
std::map<const llvm::ConstantDataVector *, unsigned> VectorConstantMap;
unsigned VectorConstantIndex;
std::set<llvm::Function*> intrinsicPrototypesAlreadyGenerated;
std::set<const llvm::Argument*> ByValParams;
unsigned FPCounter;
unsigned OpaqueCounter;
llvm::DenseMap<const llvm::Value*, unsigned> AnonValueNumbers;
unsigned NextAnonValueNumber;
std::string includeName;
int vectorWidth;
/// UnnamedStructIDs - This contains a unique ID for each struct that is
/// either anonymous or has no name.
llvm::DenseMap<llvm::StructType*, unsigned> UnnamedStructIDs;
llvm::DenseMap<llvm::ArrayType *, unsigned> ArrayIDs;
public:
static char ID;
explicit CWriter(llvm::formatted_raw_ostream &o, const char *incname,
int vecwidth)
: FunctionPass(ID), Out(o), IL(0), /* Mang(0), */ LI(0),
TheModule(0), TAsm(0), MRI(0), MOFI(0), TCtx(0), TD(0),
OpaqueCounter(0), NextAnonValueNumber(0),
includeName(incname ? incname : "generic_defs.h"),
vectorWidth(vecwidth) {
initializeLoopInfoPass(*llvm::PassRegistry::getPassRegistry());
FPCounter = 0;
VectorConstantIndex = 0;
}
virtual const char *getPassName() const { return "C backend"; }
void getAnalysisUsage(llvm::AnalysisUsage &AU) const {
AU.addRequired<llvm::LoopInfo>();
AU.setPreservesAll();
}
virtual bool doInitialization(llvm::Module &M);
bool runOnFunction(llvm::Function &F) {
// Do not codegen any 'available_externally' functions at all, they have
// definitions outside the translation unit.
if (F.hasAvailableExternallyLinkage())
return false;
LI = &getAnalysis<llvm::LoopInfo>();
// Get rid of intrinsics we can't handle.
lowerIntrinsics(F);
// Output all floating point constants that cannot be printed accurately.
printFloatingPointConstants(F);
// Output all vector constants so they can be accessed with single
// vector loads
printVectorConstants(F);
printFunction(F);
return false;
}
virtual bool doFinalization(llvm::Module &M) {
// Free memory...
delete IL;
delete TD;
//delete Mang;
delete TCtx;
delete TAsm;
delete MRI;
delete MOFI;
FPConstantMap.clear();
VectorConstantMap.clear();
ByValParams.clear();
intrinsicPrototypesAlreadyGenerated.clear();
UnnamedStructIDs.clear();
ArrayIDs.clear();
return false;
}
llvm::raw_ostream &printType(llvm::raw_ostream &Out, llvm::Type *Ty,
bool isSigned = false,
const std::string &VariableName = "",
bool IgnoreName = false,
#if defined(LLVM_3_2)
const llvm::AttrListPtr &PAL = llvm::AttrListPtr()
#else
const llvm::AttributeSet &PAL = llvm::AttributeSet()
#endif
);
llvm::raw_ostream &printSimpleType(llvm::raw_ostream &Out, llvm::Type *Ty,
bool isSigned,
const std::string &NameSoFar = "");
void printStructReturnPointerFunctionType(llvm::raw_ostream &Out,
#if defined(LLVM_3_2)
const llvm::AttrListPtr &PAL,
#else
const llvm::AttributeSet &PAL,
#endif
llvm::PointerType *Ty);
std::string getStructName(llvm::StructType *ST);
std::string getArrayName(llvm::ArrayType *AT);
/// writeOperandDeref - Print the result of dereferencing the specified
/// operand with '*'. This is equivalent to printing '*' then using
/// writeOperand, but avoids excess syntax in some cases.
void writeOperandDeref(llvm::Value *Operand) {
if (isAddressExposed(Operand)) {
// Already something with an address exposed.
writeOperandInternal(Operand);
} else {
Out << "*(";
writeOperand(Operand);
Out << ")";
}
}
void writeOperand(llvm::Value *Operand, bool Static = false);
void writeInstComputationInline(llvm::Instruction &I);
void writeOperandInternal(llvm::Value *Operand, bool Static = false);
void writeOperandWithCast(llvm::Value* Operand, unsigned Opcode);
void writeOperandWithCast(llvm::Value* Operand, const llvm::ICmpInst &I);
bool writeInstructionCast(const llvm::Instruction &I);
void writeMemoryAccess(llvm::Value *Operand, llvm::Type *OperandType,
bool IsVolatile, unsigned Alignment);
private :
void lowerIntrinsics(llvm::Function &F);
/// Prints the definition of the intrinsic function F. Supports the
/// intrinsics which need to be explicitly defined in the CBackend.
void printIntrinsicDefinition(const llvm::Function &F, llvm::raw_ostream &Out);
void printModuleTypes();
void printContainedStructs(llvm::Type *Ty, llvm::SmallPtrSet<llvm::Type *, 16> &);
void printContainedArrays(llvm::ArrayType *ATy, llvm::SmallPtrSet<llvm::Type *, 16> &);
void printFloatingPointConstants(llvm::Function &F);
void printFloatingPointConstants(const llvm::Constant *C);
void printVectorConstants(llvm::Function &F);
void printFunctionSignature(const llvm::Function *F, bool Prototype);
void printFunction(llvm::Function &);
void printBasicBlock(llvm::BasicBlock *BB);
void printLoop(llvm::Loop *L);
bool printCast(unsigned opcode, llvm::Type *SrcTy, llvm::Type *DstTy);
void printConstant(llvm::Constant *CPV, bool Static);
void printConstantWithCast(llvm::Constant *CPV, unsigned Opcode);
bool printConstExprCast(const llvm::ConstantExpr *CE, bool Static);
void printConstantArray(llvm::ConstantArray *CPA, bool Static);
void printConstantVector(llvm::ConstantVector *CV, bool Static);
void printConstantDataSequential(llvm::ConstantDataSequential *CDS, bool Static);
/// isAddressExposed - Return true if the specified value's name needs to
/// have its address taken in order to get a C value of the correct type.
/// This happens for global variables, byval parameters, and direct allocas.
bool isAddressExposed(const llvm::Value *V) const {
if (const llvm::Argument *A = llvm::dyn_cast<llvm::Argument>(V))
return ByValParams.count(A);
return llvm::isa<llvm::GlobalVariable>(V) || isDirectAlloca(V);
}
// isInlinableInst - Attempt to inline instructions into their uses to build
// trees as much as possible. To do this, we have to consistently decide
// what is acceptable to inline, so that variable declarations don't get
// printed and an extra copy of the expr is not emitted.
//
static bool isInlinableInst(const llvm::Instruction &I) {
// Always inline cmp instructions, even if they are shared by multiple
// expressions. GCC generates horrible code if we don't.
if (llvm::isa<llvm::CmpInst>(I) && llvm::isa<llvm::VectorType>(I.getType()) == false)
return true;
// Must be an expression, must be used exactly once. If it is dead, we
// emit it inline where it would go.
if (I.getType() == llvm::Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
llvm::isa<llvm::TerminatorInst>(I) || llvm::isa<llvm::CallInst>(I) || llvm::isa<llvm::PHINode>(I) ||
llvm::isa<llvm::LoadInst>(I) || llvm::isa<llvm::VAArgInst>(I) || llvm::isa<llvm::InsertElementInst>(I) ||
llvm::isa<llvm::InsertValueInst>(I) || llvm::isa<llvm::ExtractValueInst>(I) || llvm::isa<llvm::SelectInst>(I))
// Don't inline a load across a store or other bad things!
return false;
// Must not be used in inline asm, extractelement, or shufflevector.
if (I.hasOneUse()) {
#if !defined(LLVM_3_2) && !defined(LLVM_3_3) && !defined(LLVM_3_4)
const llvm::Instruction &User = llvm::cast<llvm::Instruction>(*I.user_back());
#else
const llvm::Instruction &User = llvm::cast<llvm::Instruction>(*I.use_back());
#endif
if (isInlineAsm(User) || llvm::isa<llvm::ExtractElementInst>(User) ||
llvm::isa<llvm::ShuffleVectorInst>(User) || llvm::isa<llvm::AtomicRMWInst>(User) ||
llvm::isa<llvm::AtomicCmpXchgInst>(User))
return false;
}
// Only inline instruction it if it's use is in the same BB as the inst.
#if !defined(LLVM_3_2) && !defined(LLVM_3_3) && !defined(LLVM_3_4)
return I.getParent() == llvm::cast<llvm::Instruction>(I.user_back())->getParent();
#else
return I.getParent() == llvm::cast<llvm::Instruction>(I.use_back())->getParent();
#endif
}
// isDirectAlloca - Define fixed sized allocas in the entry block as direct
// variables which are accessed with the & operator. This causes GCC to
// generate significantly better code than to emit alloca calls directly.
//
static const llvm::AllocaInst *isDirectAlloca(const llvm::Value *V) {
const llvm::AllocaInst *AI = llvm::dyn_cast<llvm::AllocaInst>(V);
if (!AI) return 0;
if (AI->isArrayAllocation())
return 0; // FIXME: we can also inline fixed size array allocas!
if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
return 0;
return AI;
}
// isInlineAsm - Check if the instruction is a call to an inline asm chunk.
static bool isInlineAsm(const llvm::Instruction& I) {
if (const llvm::CallInst *CI = llvm::dyn_cast<llvm::CallInst>(&I))
return llvm::isa<llvm::InlineAsm>(CI->getCalledValue());
return false;
}
// Instruction visitation functions
friend class llvm::InstVisitor<CWriter>;
void visitReturnInst(llvm::ReturnInst &I);
void visitBranchInst(llvm::BranchInst &I);
void visitSwitchInst(llvm::SwitchInst &I);
void visitIndirectBrInst(llvm::IndirectBrInst &I);
void visitInvokeInst(llvm::InvokeInst &I) {
llvm_unreachable("Lowerinvoke pass didn't work!");
}
void visitResumeInst(llvm::ResumeInst &I) {
llvm_unreachable("DwarfEHPrepare pass didn't work!");
}
void visitUnreachableInst(llvm::UnreachableInst &I);
void visitPHINode(llvm::PHINode &I);
void visitBinaryOperator(llvm::Instruction &I);
void visitICmpInst(llvm::ICmpInst &I);
void visitFCmpInst(llvm::FCmpInst &I);
void visitCastInst (llvm::CastInst &I);
void visitSelectInst(llvm::SelectInst &I);
void visitCallInst (llvm::CallInst &I);
void visitInlineAsm(llvm::CallInst &I);
bool visitBuiltinCall(llvm::CallInst &I, llvm::Intrinsic::ID ID, bool &WroteCallee);
void visitAllocaInst(llvm::AllocaInst &I);
void visitLoadInst (llvm::LoadInst &I);
void visitStoreInst (llvm::StoreInst &I);
void visitGetElementPtrInst(llvm::GetElementPtrInst &I);
void visitVAArgInst (llvm::VAArgInst &I);
void visitInsertElementInst(llvm::InsertElementInst &I);
void visitExtractElementInst(llvm::ExtractElementInst &I);
void visitShuffleVectorInst(llvm::ShuffleVectorInst &SVI);
void visitInsertValueInst(llvm::InsertValueInst &I);
void visitExtractValueInst(llvm::ExtractValueInst &I);
void visitAtomicRMWInst(llvm::AtomicRMWInst &I);
void visitAtomicCmpXchgInst(llvm::AtomicCmpXchgInst &I);
void visitInstruction(llvm::Instruction &I) {
#ifndef NDEBUG
llvm::errs() << "C Writer does not know about " << I;
#endif
llvm_unreachable(0);
}
void outputLValue(llvm::Instruction *I) {
Out << " " << GetValueName(I) << " = ";
}
bool isGotoCodeNecessary(llvm::BasicBlock *From, llvm::BasicBlock *To);
void printPHICopiesForSuccessor(llvm::BasicBlock *CurBlock,
llvm::BasicBlock *Successor, unsigned Indent);
void printBranchToBlock(llvm::BasicBlock *CurBlock, llvm::BasicBlock *SuccBlock,
unsigned Indent);
void printGEPExpression(llvm::Value *Ptr, llvm::gep_type_iterator I,
llvm::gep_type_iterator E, bool Static);
std::string GetValueName(const llvm::Value *Operand);
};
}
char CWriter::ID = 0;
static std::string CBEMangle(const std::string &S) {
std::string Result;
for (unsigned i = 0, e = S.size(); i != e; ++i) {
if (i+1 != e && ((S[i] == '>' && S[i+1] == '>') ||
(S[i] == '<' && S[i+1] == '<'))) {
Result += '_';
Result += 'A'+(S[i]&15);
Result += 'A'+((S[i]>>4)&15);
Result += '_';
i++;
} else if (isalnum(S[i]) || S[i] == '_' || S[i] == '<' || S[i] == '>') {
Result += S[i];
} else {
Result += '_';
Result += 'A'+(S[i]&15);
Result += 'A'+((S[i]>>4)&15);
Result += '_';
}
}
return Result;
}
std::string CWriter::getStructName(llvm::StructType *ST) {
if (!ST->isLiteral() && !ST->getName().empty())
return CBEMangle("l_"+ST->getName().str());
return "l_unnamed_" + llvm::utostr(UnnamedStructIDs[ST]);
}
std::string CWriter::getArrayName(llvm::ArrayType *AT) {
return "l_array_" + llvm::utostr(ArrayIDs[AT]);
}
/// printStructReturnPointerFunctionType - This is like printType for a struct
/// return type, except, instead of printing the type as void (*)(Struct*, ...)
/// print it as "Struct (*)(...)", for struct return functions.
void CWriter::printStructReturnPointerFunctionType(llvm::raw_ostream &Out,
#if defined(LLVM_3_2)
const llvm::AttrListPtr &PAL,
#else
const llvm::AttributeSet &PAL,
#endif
llvm::PointerType *TheTy) {
llvm::FunctionType *FTy = llvm::cast<llvm::FunctionType>(TheTy->getElementType());
std::string tstr;
llvm::raw_string_ostream FunctionInnards(tstr);
FunctionInnards << " (*) (";
bool PrintedType = false;
llvm::FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
llvm::Type *RetTy = llvm::cast<llvm::PointerType>(*I)->getElementType();
unsigned Idx = 1;
for (++I, ++Idx; I != E; ++I, ++Idx) {
if (PrintedType)
FunctionInnards << ", ";
llvm::Type *ArgTy = *I;
#if defined(LLVM_3_2)
if (PAL.getParamAttributes(Idx).hasAttribute(llvm::Attributes::ByVal)) {
#else
if (PAL.getParamAttributes(Idx).hasAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::ByVal)) {
#endif
assert(ArgTy->isPointerTy());
ArgTy = llvm::cast<llvm::PointerType>(ArgTy)->getElementType();
}
printType(FunctionInnards, ArgTy,
#if defined(LLVM_3_2)
PAL.getParamAttributes(Idx).hasAttribute(llvm::Attributes::SExt),
#else
PAL.getParamAttributes(Idx).hasAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::SExt),
#endif
"");
PrintedType = true;
}
if (FTy->isVarArg()) {
if (!PrintedType)
FunctionInnards << " int"; //dummy argument for empty vararg functs
FunctionInnards << ", ...";
} else if (!PrintedType) {
FunctionInnards << "void";
}
FunctionInnards << ')';
printType(Out, RetTy,
#if defined(LLVM_3_2)
PAL.getParamAttributes(0).hasAttribute(llvm::Attributes::SExt),
#else
PAL.getParamAttributes(0).hasAttribute(llvm::AttributeSet::ReturnIndex, llvm::Attribute::SExt),
#endif
FunctionInnards.str());
}
llvm::raw_ostream &
CWriter::printSimpleType(llvm::raw_ostream &Out, llvm::Type *Ty, bool isSigned,
const std::string &NameSoFar) {
assert((Ty->isFloatingPointTy() || Ty->isX86_MMXTy() || Ty->isIntegerTy() || Ty->isVectorTy() || Ty->isVoidTy()) &&
"Invalid type for printSimpleType");
switch (Ty->getTypeID()) {
case llvm::Type::VoidTyID: return Out << "void " << NameSoFar;
case llvm::Type::IntegerTyID: {
unsigned NumBits = llvm::cast<llvm::IntegerType>(Ty)->getBitWidth();
if (NumBits == 1)
return Out << "bool " << NameSoFar;
else if (NumBits <= 8)
return Out << (isSigned?"":"u") << "int8_t " << NameSoFar;
else if (NumBits <= 16)
return Out << (isSigned?"":"u") << "int16_t " << NameSoFar;
else if (NumBits <= 32)
return Out << (isSigned?"":"u") << "int32_t " << NameSoFar;
else if (NumBits <= 64)
return Out << (isSigned?"":"u") << "int64_t "<< NameSoFar;
else {
assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
}
}
case llvm::Type::FloatTyID: return Out << "float " << NameSoFar;
case llvm::Type::DoubleTyID: return Out << "double " << NameSoFar;
// Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
// present matches host 'long double'.
case llvm::Type::X86_FP80TyID:
case llvm::Type::PPC_FP128TyID:
case llvm::Type::FP128TyID: return Out << "long double " << NameSoFar;
case llvm::Type::X86_MMXTyID:
return printSimpleType(Out, llvm::Type::getInt32Ty(Ty->getContext()), isSigned,
" __attribute__((vector_size(64))) " + NameSoFar);
case llvm::Type::VectorTyID: {
llvm::VectorType *VTy = llvm::cast<llvm::VectorType>(Ty);
#if 1
const char *suffix = NULL;
const llvm::Type *eltTy = VTy->getElementType();
if (eltTy->isFloatTy())
suffix = "f";
else if (eltTy->isDoubleTy())
suffix = "d";
else {
assert(eltTy->isIntegerTy());
switch (eltTy->getPrimitiveSizeInBits()) {
case 1:
suffix = "i1";
break;
case 8:
suffix = "i8";
break;
case 16:
suffix = "i16";
break;
case 32:
suffix = "i32";
break;
case 64:
suffix = "i64";
break;
default:
llvm::report_fatal_error("Only integer types of size 8/16/32/64 are "
"supported by the C++ backend.");
}
}
return Out << "__vec" << VTy->getNumElements() << "_" << suffix << " " <<
NameSoFar;
#else
return printSimpleType(Out, VTy->getElementType(), isSigned,
" __attribute__((vector_size(" +
utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
#endif
}
default:
#ifndef NDEBUG
llvm::errs() << "Unknown primitive type: " << *Ty << "\n";
#endif
llvm_unreachable(0);
}
}
// Pass the Type* and the variable name and this prints out the variable
// declaration.
//
llvm::raw_ostream &CWriter::printType(llvm::raw_ostream &Out, llvm::Type *Ty,
bool isSigned, const std::string &NameSoFar,
bool IgnoreName,
#if defined(LLVM_3_2)
const llvm::AttrListPtr &PAL
#else
const llvm::AttributeSet &PAL
#endif
) {
if (Ty->isFloatingPointTy() || Ty->isX86_MMXTy() || Ty->isIntegerTy() || Ty->isVectorTy() || Ty->isVoidTy()) {
printSimpleType(Out, Ty, isSigned, NameSoFar);
return Out;
}
switch (Ty->getTypeID()) {
case llvm::Type::FunctionTyID: {
llvm::FunctionType *FTy = llvm::cast<llvm::FunctionType>(Ty);
std::string tstr;
llvm::raw_string_ostream FunctionInnards(tstr);
FunctionInnards << " (" << NameSoFar << ") (";
unsigned Idx = 1;
for (llvm::FunctionType::param_iterator I = FTy->param_begin(),
E = FTy->param_end(); I != E; ++I) {
llvm::Type *ArgTy = *I;
#if defined(LLVM_3_2)
if (PAL.getParamAttributes(Idx).hasAttribute(llvm::Attributes::ByVal)) {
#else
if (PAL.getParamAttributes(Idx).hasAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::ByVal)) {
#endif
assert(ArgTy->isPointerTy());
ArgTy = llvm::cast<llvm::PointerType>(ArgTy)->getElementType();
}
if (I != FTy->param_begin())
FunctionInnards << ", ";
printType(FunctionInnards, ArgTy,
#if defined(LLVM_3_2)
PAL.getParamAttributes(Idx).hasAttribute(llvm::Attributes::SExt),
#else
PAL.getParamAttributes(Idx).hasAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::SExt),
#endif
"");
++Idx;
}
if (FTy->isVarArg()) {
if (!FTy->getNumParams())
FunctionInnards << " int"; //dummy argument for empty vaarg functs
FunctionInnards << ", ...";
} else if (!FTy->getNumParams()) {
FunctionInnards << "void";
}
FunctionInnards << ')';
printType(Out, FTy->getReturnType(),
#if defined(LLVM_3_2)
PAL.getParamAttributes(0).hasAttribute(llvm::Attributes::SExt),
#else
PAL.getParamAttributes(0).hasAttribute(llvm::AttributeSet::ReturnIndex, llvm::Attribute::SExt),
#endif
FunctionInnards.str());
return Out;
}
case llvm::Type::StructTyID: {
llvm::StructType *STy = llvm::cast<llvm::StructType>(Ty);
// Check to see if the type is named.
if (!IgnoreName)
return Out << getStructName(STy) << ' ' << NameSoFar;
Out << "struct " << NameSoFar << " {\n";
// print initialization func
if (STy->getNumElements() > 0) {
Out << " static " << NameSoFar << " init(";
unsigned Idx = 0;
for (llvm::StructType::element_iterator I = STy->element_begin(),
E = STy->element_end(); I != E; ++I, ++Idx) {
char buf[64];
sprintf(buf, "v%d", Idx);
printType(Out, *I, false, buf);
if (Idx + 1 < STy->getNumElements())
Out << ", ";
}
Out << ") {\n";
Out << " " << NameSoFar << " ret;\n";
for (Idx = 0; Idx < STy->getNumElements(); ++Idx)
Out << " ret.field" << Idx << " = v" << Idx << ";\n";
Out << " return ret;\n";
Out << " }\n";
}
unsigned Idx = 0;
for (llvm::StructType::element_iterator I = STy->element_begin(),
E = STy->element_end(); I != E; ++I) {
Out << " ";
printType(Out, *I, false, "field" + llvm::utostr(Idx++));
Out << ";\n";
}
Out << '}';
if (STy->isPacked())
Out << " __attribute__ ((packed))";
return Out;
}
case llvm::Type::PointerTyID: {
llvm::PointerType *PTy = llvm::cast<llvm::PointerType>(Ty);
std::string ptrName = "*" + NameSoFar;
if (PTy->getElementType()->isArrayTy() ||
PTy->getElementType()->isVectorTy())
ptrName = "(" + ptrName + ")";
if (!PAL.isEmpty())
// Must be a function ptr cast!
return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
return printType(Out, PTy->getElementType(), false, ptrName);
}
case llvm::Type::ArrayTyID: {
llvm::ArrayType *ATy = llvm::cast<llvm::ArrayType>(Ty);
// Check to see if the type is named.
if (!IgnoreName)
return Out << getArrayName(ATy) << ' ' << NameSoFar;
unsigned NumElements = (unsigned)ATy->getNumElements();
if (NumElements == 0) NumElements = 1;
// Arrays are wrapped in structs to allow them to have normal
// value semantics (avoiding the array "decay").
Out << "struct " << NameSoFar << " {\n";
// init func
Out << " static " << NameSoFar << " init(";
for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
char buf[64];
sprintf(buf, "v%d", Idx);
printType(Out, ATy->getElementType(), false, buf);
if (Idx + 1 < NumElements)
Out << ", ";
}
Out << ") {\n";
Out << " " << NameSoFar << " ret;\n";
for (unsigned Idx = 0; Idx < NumElements; ++Idx)
Out << " ret.array[" << Idx << "] = v" << Idx << ";\n";
Out << " return ret;\n";
Out << " }\n ";
// if it's an array of i8s, also provide a version that takes a const
// char *
if (ATy->getElementType() == LLVMTypes::Int8Type) {
Out << " static " << NameSoFar << " init(const char *p) {\n";
Out << " " << NameSoFar << " ret;\n";
Out << " memcpy((uint8_t *)ret.array, (uint8_t *)p, " << NumElements << ");\n";
Out << " return ret;\n";
Out << " }\n";
}
printType(Out, ATy->getElementType(), false,
"array[" + llvm::utostr(NumElements) + "]");
return Out << ";\n} ";
}
default:
llvm_unreachable("Unhandled case in getTypeProps!");
}
}
void CWriter::printConstantArray(llvm::ConstantArray *CPA, bool Static) {
printConstant(llvm::cast<llvm::Constant>(CPA->getOperand(0)), Static);
for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
Out << ", ";
printConstant(llvm::cast<llvm::Constant>(CPA->getOperand(i)), Static);
}
}
void CWriter::printConstantVector(llvm::ConstantVector *CP, bool Static) {
printConstant(llvm::cast<llvm::Constant>(CP->getOperand(0)), Static);
for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
Out << ", ";
printConstant(llvm::cast<llvm::Constant>(CP->getOperand(i)), Static);
}
}
void CWriter::printConstantDataSequential(llvm::ConstantDataSequential *CDS,
bool Static) {
// As a special case, print the array as a string if it is an array of
// ubytes or an array of sbytes with positive values.
//
if (CDS->isCString()) {
Out << '\"';
// Keep track of whether the last number was a hexadecimal escape.
bool LastWasHex = false;
llvm::StringRef Bytes = CDS->getAsCString();
// Do not include the last character, which we know is null
for (unsigned i = 0, e = Bytes.size(); i != e; ++i) {
unsigned char C = Bytes[i];
// Print it out literally if it is a printable character. The only thing
// to be careful about is when the last letter output was a hex escape
// code, in which case we have to be careful not to print out hex digits
// explicitly (the C compiler thinks it is a continuation of the previous
// character, sheesh...)
//
if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
LastWasHex = false;
if (C == '"' || C == '\\')
Out << "\\" << (char)C;
else
Out << (char)C;
} else {
LastWasHex = false;
switch (C) {
case '\n': Out << "\\n"; break;
case '\t': Out << "\\t"; break;
case '\r': Out << "\\r"; break;
case '\v': Out << "\\v"; break;
case '\a': Out << "\\a"; break;
case '\"': Out << "\\\""; break;
case '\'': Out << "\\\'"; break;
default:
Out << "\\x";
Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
LastWasHex = true;
break;
}
}
}
Out << '\"';
} else {
printConstant(CDS->getElementAsConstant(0), Static);
for (unsigned i = 1, e = CDS->getNumElements(); i != e; ++i) {
Out << ", ";