summaryrefslogtreecommitdiff
path: root/mcs/mcs/convert.cs
blob: e2e1268f35656e952f8299d8324dd67928b35faa (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
//
// conversion.cs: various routines for implementing conversions.
//
// Authors:
//   Miguel de Icaza (miguel@ximian.com)
//   Ravi Pratap (ravi@ximian.com)
//   Marek Safar (marek.safar@gmail.com)
//
// Copyright 2001, 2002, 2003 Ximian, Inc.
// Copyright 2003-2008 Novell, Inc.
// Copyright 2011 Xamarin Inc (http://www.xamarin.com)
//

using System;
using System.Collections.Generic;

#if STATIC
using IKVM.Reflection.Emit;
#else
using System.Reflection.Emit;
#endif

namespace Mono.CSharp {

	//
	// A container class for all the conversion operations
	//
	static class Convert
	{
		//
		// From a one-dimensional array-type S[] to System.Collections.IList<T> and base
		// interfaces of this interface, provided there is an implicit reference conversion
		// from S to T.
		//
		static bool ArrayToIList (ArrayContainer array, TypeSpec list, bool isExplicit)
		{
			if (array.Rank != 1 || !list.IsArrayGenericInterface)
				return false;

			var arg_type = list.TypeArguments[0];
			if (array.Element == arg_type)
				return true;

			//
			// Reject conversion from T[] to IList<U> even if T has U dependency
			//
			if (arg_type.IsGenericParameter)
				return false;

			if (isExplicit)
				return ExplicitReferenceConversionExists (array.Element, arg_type);

			return ImplicitReferenceConversionExists (array.Element, arg_type);
		}
		
		static bool IList_To_Array(TypeSpec list, ArrayContainer array)
		{
			if (array.Rank != 1 || !list.IsArrayGenericInterface)
				return false;

			var arg_type = list.TypeArguments[0];
			if (array.Element == arg_type)
				return true;
			
			return ImplicitReferenceConversionExists (array.Element, arg_type) || ExplicitReferenceConversionExists (array.Element, arg_type);
		}

		public static Expression ImplicitTypeParameterConversion (Expression expr, TypeParameterSpec expr_type, TypeSpec target_type)
		{
			//
			// From T to a type parameter U, provided T depends on U
			//
			if (target_type.IsGenericParameter) {
				if (expr_type.TypeArguments != null) {
					foreach (var targ in expr_type.TypeArguments) {
						if (!TypeSpecComparer.Override.IsEqual (target_type, targ))
							continue;

						if (expr == null)
							return EmptyExpression.Null;

						if (expr_type.IsReferenceType && !((TypeParameterSpec)target_type).IsReferenceType)
							return new BoxedCast (expr, target_type);

						return new ClassCast (expr, target_type);
					}
				}

				return null;
			}

			//
			// LAMESPEC: From T to dynamic type because it's like T to object
			//
			if (target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
				if (expr == null)
					return EmptyExpression.Null;

				if (expr_type.IsReferenceType)
					return new ClassCast (expr, target_type);

				return new BoxedCast (expr, target_type);
			}

			//
			// From T to its effective base class C
			// From T to any base class of C (it cannot contain dynamic or be of dynamic type)
			// From T to any interface implemented by C
			//
			var base_type = expr_type.GetEffectiveBase ();
			if (base_type == target_type || TypeSpec.IsBaseClass (base_type, target_type, false) || base_type.ImplementsInterface (target_type, true)) {
				if (expr == null)
					return EmptyExpression.Null;

				if (expr_type.IsReferenceType)
					return new ClassCast (expr, target_type);

				return new BoxedCast (expr, target_type);
			}

			if (target_type.IsInterface && expr_type.IsConvertibleToInterface (target_type)) {
				if (expr == null)
					return EmptyExpression.Null;

				if (expr_type.IsReferenceType)
					return new ClassCast (expr, target_type);

				return new BoxedCast (expr, target_type);
			}

			return null;
		}

		static Expression ExplicitTypeParameterConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
		{
			var target_tp = target_type as TypeParameterSpec;
			if (target_tp != null) {
				if (target_tp.TypeArguments != null) {
					foreach (var targ in target_tp.TypeArguments) {
						if (!TypeSpecComparer.Override.IsEqual (source_type, targ))
							continue;

						return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
					}
				}
/*
				if (target_tp.Interfaces != null) {
					foreach (TypeSpec iface in target_tp.Interfaces) {
						if (!TypeManager.IsGenericParameter (iface))
							continue;

						if (TypeManager.IsSubclassOf (source_type, iface))
							return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
					}
				}
*/
				return null;
			}

			if (target_type.IsInterface)
				return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);

			return null;
		}

		public static Expression ImplicitReferenceConversion (Expression expr, TypeSpec target_type, bool explicit_cast)
		{
			TypeSpec expr_type = expr.Type;

			if (expr_type.Kind == MemberKind.TypeParameter)
				return ImplicitTypeParameterConversion (expr, (TypeParameterSpec) expr.Type, target_type);

			//
			// from the null type to any reference-type.
			//
			NullLiteral nl = expr as NullLiteral;
			if (nl != null) {
				return nl.ConvertImplicitly (target_type);
			}

			if (ImplicitReferenceConversionExists (expr_type, target_type)) {
				// 
				// Avoid wrapping implicitly convertible reference type
				//
				if (!explicit_cast)
					return expr;

				return EmptyCast.Create (expr, target_type);
			}

			return null;
		}

		//
		// Implicit reference conversions
		//
		public static bool ImplicitReferenceConversionExists (TypeSpec expr_type, TypeSpec target_type)
		{
			return ImplicitReferenceConversionExists (expr_type, target_type, true);
		}

		public static bool ImplicitReferenceConversionExists (TypeSpec expr_type, TypeSpec target_type, bool refOnlyTypeParameter)
		{
			// It's here only to speed things up
			if (target_type.IsStruct)
				return false;

			switch (expr_type.Kind) {
			case MemberKind.TypeParameter:
				return ImplicitTypeParameterConversion (null, (TypeParameterSpec) expr_type, target_type) != null &&
					(!refOnlyTypeParameter || TypeSpec.IsReferenceType (expr_type));

			case MemberKind.Class:
				//
				// From any class-type to dynamic (+object to speed up common path)
				//
				if (target_type.BuiltinType == BuiltinTypeSpec.Type.Object || target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
					return true;

				if (target_type.IsClass) {
					//
					// Identity conversion, including dynamic erasure
					//
					if (TypeSpecComparer.IsEqual (expr_type, target_type))
						return true;

					//
					// From any class-type S to any class-type T, provided S is derived from T
					//
					return TypeSpec.IsBaseClass (expr_type, target_type, true);
				}

				//
				// From any class-type S to any interface-type T, provided S implements T
				//
				if (target_type.IsInterface)
					return expr_type.ImplementsInterface (target_type, true);

				return false;

			case MemberKind.ArrayType:
				//
				// Identity array conversion
				//
				if (expr_type == target_type)
					return true;

				//
				// From any array-type to System.Array
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Array:
				case BuiltinTypeSpec.Type.Object:
				case BuiltinTypeSpec.Type.Dynamic:
					return true;
				}

				var expr_type_array = (ArrayContainer) expr_type;
				var target_type_array = target_type as ArrayContainer;

				//
				// From an array-type S to an array-type of type T
				//
				if (target_type_array != null && expr_type_array.Rank == target_type_array.Rank) {

					//
					// Both SE and TE are reference-types. TE check is defered
					// to ImplicitReferenceConversionExists
					//
					TypeSpec expr_element_type = expr_type_array.Element;
					if (!TypeSpec.IsReferenceType (expr_element_type))
						return false;

					//
					// An implicit reference conversion exists from SE to TE
					//
					return ImplicitReferenceConversionExists (expr_element_type, target_type_array.Element);
				}

				//
				// From any array-type to the interfaces it implements
				//
				if (target_type.IsInterface) {
					if (expr_type.ImplementsInterface (target_type, false))
						return true;

					// from an array-type of type T to IList<T>
					if (ArrayToIList (expr_type_array, target_type, false))
						return true;
				}

				return false;

			case MemberKind.Delegate:
				//
				// From any delegate-type to System.Delegate (and its base types)
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Delegate:
				case BuiltinTypeSpec.Type.MulticastDelegate:
				case BuiltinTypeSpec.Type.Object:
				case BuiltinTypeSpec.Type.Dynamic:
					return true;
				}

				//
				// Identity conversion, including dynamic erasure
				//
				if (TypeSpecComparer.IsEqual (expr_type, target_type))
					return true;

				//
				// From any delegate-type to the interfaces it implements
				// From any reference-type to an delegate type if is variance-convertible
				//
				return expr_type.ImplementsInterface (target_type, false) || TypeSpecComparer.Variant.IsEqual (expr_type, target_type);

			case MemberKind.Interface:
				//
				// Identity conversion, including dynamic erasure
				//
				if (TypeSpecComparer.IsEqual (expr_type, target_type))
					return true;

				//
				// From any interface type S to interface-type T
				// From any reference-type to an interface if is variance-convertible
				//
				if (target_type.IsInterface)
					return TypeSpecComparer.Variant.IsEqual (expr_type, target_type) || expr_type.ImplementsInterface (target_type, true);

				return target_type.BuiltinType == BuiltinTypeSpec.Type.Object || target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;

			case MemberKind.InternalCompilerType:
				//
				// from the null literal to any reference-type.
				//
				if (expr_type == InternalType.NullLiteral) {
					// Exlude internal compiler types
					if (target_type.Kind == MemberKind.InternalCompilerType)
						return target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;

					return TypeSpec.IsReferenceType (target_type);
				}

				//
				// Implicit dynamic conversion
				//
				if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
					switch (target_type.Kind) {
					case MemberKind.ArrayType:
					case MemberKind.Class:
					case MemberKind.Delegate:
					case MemberKind.Interface:
					case MemberKind.TypeParameter:
						return true;
					}

					// dynamic to __arglist
					if (target_type == InternalType.Arglist)
						return true;

					return false;
				}

				break;
			}

			return false;
		}

		public static Expression ImplicitBoxingConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
		{
			switch (target_type.BuiltinType) {
			//
			// From any non-nullable-value-type to the type object and dynamic
			//
			case BuiltinTypeSpec.Type.Object:
			case BuiltinTypeSpec.Type.Dynamic:
			//
			// From any non-nullable-value-type to the type System.ValueType
			//
			case BuiltinTypeSpec.Type.ValueType:
				//
				// No ned to check for nullable type as underlying type is always convertible
				//
				if (!TypeSpec.IsValueType (expr_type))
					return null;

				return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);

			case BuiltinTypeSpec.Type.Enum:
				//
				// From any enum-type to the type System.Enum.
				//
				if (expr_type.IsEnum)
					return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);

				break;
			}

			//
			// From a nullable-type to a reference type, if a boxing conversion exists from
			// the underlying type to the reference type
			//
			if (expr_type.IsNullableType) {
				if (!TypeSpec.IsReferenceType (target_type))
					return null;

				var res = ImplicitBoxingConversion (expr, Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type);

				// "cast" underlying type to target type to emit correct InvalidCastException when
				// underlying hierarchy changes without recompilation
				if (res != null && expr != null)
					res = new UnboxCast (res, target_type);

				return res;
			}

			//
			// A value type has a boxing conversion to an interface type I if it has a boxing conversion
			// to an interface or delegate type I0 and I0 is variance-convertible to I
			//
			if (target_type.IsInterface && TypeSpec.IsValueType (expr_type) && expr_type.ImplementsInterface (target_type, true)) {
				return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
			}

			return null;
		}

		public static Expression ImplicitNulableConversion (ResolveContext ec, Expression expr, TypeSpec target_type)
		{
			TypeSpec expr_type = expr.Type;

			//
			// From null to any nullable type
			//
			if (expr_type == InternalType.NullLiteral)
				return ec == null ? EmptyExpression.Null : Nullable.LiftedNull.Create (target_type, expr.Location);

			// S -> T?
			TypeSpec t_el = Nullable.NullableInfo.GetUnderlyingType (target_type);

			// S? -> T?
			if (expr_type.IsNullableType)
				expr_type = Nullable.NullableInfo.GetUnderlyingType (expr_type);

			//
			// Predefined implicit identity or implicit numeric conversion
			// has to exist between underlying type S and underlying type T
			//

			// conversion exists only mode
			if (ec == null) {
				if (TypeSpecComparer.IsEqual (expr_type, t_el))
					return EmptyExpression.Null;

				if (expr is Constant)
					return ((Constant) expr).ConvertImplicitly (t_el);

				return ImplicitNumericConversion (null, expr_type, t_el);
			}

			Expression unwrap;
			if (expr_type != expr.Type)
				unwrap = Nullable.Unwrap.Create (expr);
			else
				unwrap = expr;

			Expression conv = unwrap;
			if (!TypeSpecComparer.IsEqual (expr_type, t_el)) {
				if (conv is Constant)
					conv = ((Constant)conv).ConvertImplicitly (t_el);
				else
					conv = ImplicitNumericConversion (conv, expr_type, t_el);

				if (conv == null)
					return null;
			}
			
			if (expr_type != expr.Type)
				return new Nullable.LiftedConversion (conv, unwrap, target_type).Resolve (ec);

			return Nullable.Wrap.Create (conv, target_type);
		}

		/// <summary>
		///   Implicit Numeric Conversions.
		///
		///   expr is the expression to convert, returns a new expression of type
		///   target_type or null if an implicit conversion is not possible.
		/// </summary>
		public static Expression ImplicitNumericConversion (Expression expr, TypeSpec target_type)
		{
			return ImplicitNumericConversion (expr, expr.Type, target_type);
		}

		public static bool ImplicitNumericConversionExists (TypeSpec expr_type, TypeSpec target_type)
		{
			return ImplicitNumericConversion (null, expr_type, target_type) != null;
		}

		static Expression ImplicitNumericConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
		{
			switch (expr_type.BuiltinType) {
			case BuiltinTypeSpec.Type.SByte:
				//
				// From sbyte to short, int, long, float, double, decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Int:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
				case BuiltinTypeSpec.Type.Long:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
				case BuiltinTypeSpec.Type.Double:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
				case BuiltinTypeSpec.Type.Float:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
				case BuiltinTypeSpec.Type.Short:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
				case BuiltinTypeSpec.Type.Decimal:
					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);

				}

				break;
			case BuiltinTypeSpec.Type.Byte:
				//
				// From byte to short, ushort, int, uint, long, ulong, float, double, decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Int:
				case BuiltinTypeSpec.Type.UInt:
				case BuiltinTypeSpec.Type.Short:
				case BuiltinTypeSpec.Type.UShort:
					return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
				case BuiltinTypeSpec.Type.ULong:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
				case BuiltinTypeSpec.Type.Long:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
				case BuiltinTypeSpec.Type.Float:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
				case BuiltinTypeSpec.Type.Double:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
				case BuiltinTypeSpec.Type.Decimal:
					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
				}
				break;
			case BuiltinTypeSpec.Type.Short:
				//
				// From short to int, long, float, double, decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Int:
					return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
				case BuiltinTypeSpec.Type.Long:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
				case BuiltinTypeSpec.Type.Double:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
				case BuiltinTypeSpec.Type.Float:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
				case BuiltinTypeSpec.Type.Decimal:
					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
				}
				break;
			case BuiltinTypeSpec.Type.UShort:
				//
				// From ushort to int, uint, long, ulong, float, double, decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Int:
				case BuiltinTypeSpec.Type.UInt:
					return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
				case BuiltinTypeSpec.Type.ULong:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
				case BuiltinTypeSpec.Type.Long:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
				case BuiltinTypeSpec.Type.Double:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
				case BuiltinTypeSpec.Type.Float:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
				case BuiltinTypeSpec.Type.Decimal:
					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
				}
				break;
			case BuiltinTypeSpec.Type.Int:
				//
				// From int to long, float, double, decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Long:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
				case BuiltinTypeSpec.Type.Double:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
				case BuiltinTypeSpec.Type.Float:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
				case BuiltinTypeSpec.Type.Decimal:
					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
				}
				break;
			case BuiltinTypeSpec.Type.UInt:
				//
				// From uint to long, ulong, float, double, decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Long:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
				case BuiltinTypeSpec.Type.ULong:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
				case BuiltinTypeSpec.Type.Double:
					return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R8);
				case BuiltinTypeSpec.Type.Float:
					return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R4);
				case BuiltinTypeSpec.Type.Decimal:
					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
				}
				break;
			case BuiltinTypeSpec.Type.Long:
				//
				// From long to float, double, decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Double:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
				case BuiltinTypeSpec.Type.Float:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
				case BuiltinTypeSpec.Type.Decimal:
					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
				}
				break;
			case BuiltinTypeSpec.Type.ULong:
				//
				// From ulong to float, double, decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Double:
					return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R8);
				case BuiltinTypeSpec.Type.Float:
					return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R4);
				case BuiltinTypeSpec.Type.Decimal:
					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
				}
				break;
			case BuiltinTypeSpec.Type.Char:
				//
				// From char to ushort, int, uint, long, ulong, float, double, decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.UShort:
				case BuiltinTypeSpec.Type.Int:
				case BuiltinTypeSpec.Type.UInt:
					return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
				case BuiltinTypeSpec.Type.ULong:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
				case BuiltinTypeSpec.Type.Long:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
				case BuiltinTypeSpec.Type.Float:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
				case BuiltinTypeSpec.Type.Double:
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
				case BuiltinTypeSpec.Type.Decimal:
					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
				}
				break;
			case BuiltinTypeSpec.Type.Float:
				//
				// float to double
				//
				if (target_type.BuiltinType == BuiltinTypeSpec.Type.Double)
					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
				break;
			}

			return null;
		}

		//
		// Full version of implicit conversion
		//
		public static bool ImplicitConversionExists (ResolveContext ec, Expression expr, TypeSpec target_type)
		{
			if (ImplicitStandardConversionExists (expr, target_type))
				return true;

			if (expr.Type == InternalType.AnonymousMethod) {
				if (!target_type.IsDelegate && !target_type.IsExpressionTreeType)
					return false;

				AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
				return ame.ImplicitStandardConversionExists (ec, target_type);
			}
			
			if (expr.eclass == ExprClass.MethodGroup) {
				if (target_type.IsDelegate && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
					MethodGroupExpr mg = expr as MethodGroupExpr;
					if (mg != null)
						return DelegateCreation.ImplicitStandardConversionExists (ec, mg, target_type);
				}

				return false;
			}

			// Conversion from __arglist to System.ArgIterator
			if (expr.Type == InternalType.Arglist)
				return target_type == ec.Module.PredefinedTypes.ArgIterator.TypeSpec;

			return UserDefinedConversion (ec, expr, target_type, true, true, Location.Null) != null;
		}

		//
		// Implicit standard conversion (only core conversions are used here)
		//
		public static bool ImplicitStandardConversionExists (Expression expr, TypeSpec target_type)
		{
			//
			// Identity conversions
			// Implicit numeric conversions
			// Implicit nullable conversions
			// Implicit reference conversions
			// Boxing conversions
			// Implicit constant expression conversions
			// Implicit conversions involving type parameters
			//

			TypeSpec expr_type = expr.Type;

			if (expr_type == target_type)
				return true;

			if (target_type.IsNullableType)
				return ImplicitNulableConversion (null, expr, target_type) != null;

			if (ImplicitNumericConversion (null, expr_type, target_type) != null)
				return true;

			if (ImplicitReferenceConversionExists (expr_type, target_type, false))
				return true;

			if (ImplicitBoxingConversion (null, expr_type, target_type) != null)
				return true;
			
			//
			// Implicit Constant Expression Conversions
			//
			if (expr is IntConstant){
				int value = ((IntConstant) expr).Value;
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					if (value >= SByte.MinValue && value <= SByte.MaxValue)
						return true;
					break;
				case BuiltinTypeSpec.Type.Byte:
					if (value >= 0 && value <= Byte.MaxValue)
						return true;
					break;
				case BuiltinTypeSpec.Type.Short:
					if (value >= Int16.MinValue && value <= Int16.MaxValue)
						return true;
					break;
				case BuiltinTypeSpec.Type.UShort:
					if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
						return true;
					break;
				case BuiltinTypeSpec.Type.UInt:
					if (value >= 0)
						return true;
					break;
				case BuiltinTypeSpec.Type.ULong:
					 //
					 // we can optimize this case: a positive int32
					 // always fits on a uint64.  But we need an opcode
					 // to do it.
					 //
					if (value >= 0)
						return true;

					break;
				}
			}

			if (expr is LongConstant && target_type.BuiltinType == BuiltinTypeSpec.Type.ULong){
				//
				// Try the implicit constant expression conversion
				// from long to ulong, instead of a nice routine,
				// we just inline it
				//
				long v = ((LongConstant) expr).Value;
				if (v >= 0)
					return true;
			}

			if (expr is IntegralConstant && target_type.IsEnum) {
				var i = (IntegralConstant) expr;
				//
				// LAMESPEC: csc allows any constant like 0 values to be converted, including const float f = 0.0
				//
				// An implicit enumeration conversion permits the decimal-integer-literal 0
				// to be converted to any enum-type and to any nullable-type whose underlying
				// type is an enum-type
				//
				return i.IsZeroInteger;
			}

			//
			// Implicit dynamic conversion for remaining value types. It should probably
			// go somewhere else
			//
			if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
				switch (target_type.Kind) {
				case MemberKind.Struct:
				case MemberKind.Enum:
					return true;
				}

				return false;
			}

			//
			// In an unsafe context implicit conversions is extended to include
			//
			// From any pointer-type to the type void*
			// From the null literal to any pointer-type.
			//
			// LAMESPEC: The specification claims this conversion is allowed in implicit conversion but
			// in reality implicit standard conversion uses it
			//
			if (target_type.IsPointer && expr.Type.IsPointer && ((PointerContainer) target_type).Element.Kind == MemberKind.Void)
				return true;

			//
			// Struct identity conversion, including dynamic erasure
			//
			if (expr_type.IsStruct && TypeSpecComparer.IsEqual (expr_type, target_type))
				return true;

			return false;
		}

		/// <summary>
		///  Finds "most encompassed type" according to the spec (13.4.2)
		///  amongst the methods in the MethodGroupExpr
		/// </summary>
		public static TypeSpec FindMostEncompassedType (IList<TypeSpec> types)
		{
			TypeSpec best = null;
			EmptyExpression expr;

			foreach (TypeSpec t in types) {
				if (best == null) {
					best = t;
					continue;
				}

				expr = new EmptyExpression (t);
				if (ImplicitStandardConversionExists (expr, best))
					best = t;
			}

			expr = new EmptyExpression (best);
			foreach (TypeSpec t in types) {
				if (best == t)
					continue;
				if (!ImplicitStandardConversionExists (expr, t)) {
					best = null;
					break;
				}
			}

			return best;
		}

		//
		// Finds the most encompassing type (type into which all other
		// types can convert to) amongst the types in the given set
		//
		static TypeSpec FindMostEncompassingType (IList<TypeSpec> types)
		{
			if (types.Count == 0)
				return null;

			if (types.Count == 1)
				return types [0];

			TypeSpec best = null;
			for (int i = 0; i < types.Count; ++i) {
				int ii = 0;
				for (; ii < types.Count; ++ii) {
					if (ii == i)
						continue;

					var expr = new EmptyExpression (types[ii]);
					if (!ImplicitStandardConversionExists (expr, types [i])) {
						ii = 0;
						break;
					}
				}

				if (ii == 0)
					continue;

				if (best == null) {
					best = types[i];
					continue;
				}

				// Indicates multiple best types
				return InternalType.FakeInternalType;
			}

			return best;
		}

		//
		// Finds the most specific source Sx according to the rules of the spec (13.4.4)
		// by making use of FindMostEncomp* methods. Applies the correct rules separately
		// for explicit and implicit conversion operators.
		//
		static TypeSpec FindMostSpecificSource (List<MethodSpec> list, TypeSpec sourceType, Expression source, bool apply_explicit_conv_rules)
		{
			TypeSpec[] src_types_set = null;

			//
			// Try exact match first, if any operator converts from S then Sx = S
			//
			for (int i = 0; i < list.Count; ++i) {
				TypeSpec param_type = list [i].Parameters.Types [0];

				if (param_type == sourceType)
					return param_type;

				if (src_types_set == null)
					src_types_set = new TypeSpec [list.Count];

				src_types_set [i] = param_type;
			}

			//
			// Explicit Conv rules
			//
			if (apply_explicit_conv_rules) {
				var candidate_set = new List<TypeSpec> ();

				foreach (TypeSpec param_type in src_types_set){
					if (ImplicitStandardConversionExists (source, param_type))
						candidate_set.Add (param_type);
				}

				if (candidate_set.Count != 0)
					return FindMostEncompassedType (candidate_set);
			}

			//
			// Final case
			//
			if (apply_explicit_conv_rules)
				return FindMostEncompassingType (src_types_set);
			else
				return FindMostEncompassedType (src_types_set);
		}

		/// <summary>
		///  Finds the most specific target Tx according to section 13.4.4
		/// </summary>
		static public TypeSpec FindMostSpecificTarget (IList<MethodSpec> list,
							   TypeSpec target, bool apply_explicit_conv_rules)
		{
			List<TypeSpec> tgt_types_set = null;

			//
			// If any operator converts to T then Tx = T
			//
			foreach (var mi in list){
				TypeSpec ret_type = mi.ReturnType;
				if (ret_type == target)
					return ret_type;

				if (tgt_types_set == null) {
					tgt_types_set = new List<TypeSpec> (list.Count);
				} else if (tgt_types_set.Contains (ret_type)) {
					continue;
				}

				tgt_types_set.Add (ret_type);
			}

			//
			// Explicit conv rules
			//
			if (apply_explicit_conv_rules) {
				var candidate_set = new List<TypeSpec> ();

				foreach (TypeSpec ret_type in tgt_types_set) {
					var expr = new EmptyExpression (ret_type);

					if (ImplicitStandardConversionExists (expr, target))
						candidate_set.Add (ret_type);
				}

				if (candidate_set.Count != 0)
					return FindMostEncompassingType (candidate_set);
			}

			//
			// Okay, final case !
			//
			if (apply_explicit_conv_rules)
				return FindMostEncompassedType (tgt_types_set);
			else
				return FindMostEncompassingType (tgt_types_set);
		}

		/// <summary>
		///  User-defined Implicit conversions
		/// </summary>
		static public Expression ImplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc)
		{
			return UserDefinedConversion (ec, source, target, true, false, loc);
		}

		/// <summary>
		///  User-defined Explicit conversions
		/// </summary>
		static Expression ExplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc)
		{
			return UserDefinedConversion (ec, source, target, false, false, loc);
		}

		static void FindApplicableUserDefinedConversionOperators (IList<MemberSpec> operators, Expression source, TypeSpec target, bool implicitOnly, ref List<MethodSpec> candidates)
		{
			if (source.Type.IsInterface) {
				// Neither A nor B are interface-types
				return;
			}

			// For a conversion operator to be applicable, it must be possible
			// to perform a standard conversion from the source type to
			// the operand type of the operator, and it must be possible
			// to perform a standard conversion from the result type of
			// the operator to the target type.

			Expression texpr = null;

			foreach (MethodSpec op in operators) {
				
				// Can be null because MemberCache.GetUserOperator does not resize the array
				if (op == null)
					continue;

				var t = op.Parameters.Types[0];
				if (source.Type != t && !ImplicitStandardConversionExists (source, t)) {
					if (implicitOnly)
						continue;

					if (!ImplicitStandardConversionExists (new EmptyExpression (t), source.Type))
						continue;
				}

				t = op.ReturnType;

				if (t.IsInterface)
					continue;

				if (target != t) {
					if (t.IsNullableType)
						t = Nullable.NullableInfo.GetUnderlyingType (t);

					if (!ImplicitStandardConversionExists (new EmptyExpression (t), target)) {
						if (implicitOnly)
							continue;

						if (texpr == null)
							texpr = new EmptyExpression (target);

						if (!ImplicitStandardConversionExists (texpr, t))
							continue;
					}
				}

				if (candidates == null)
					candidates = new List<MethodSpec> ();

				candidates.Add (op);
			}
		}

		//
		// User-defined conversions
		//
		static Expression UserDefinedConversion (ResolveContext ec, Expression source, TypeSpec target, bool implicitOnly, bool probingOnly, Location loc)
		{
			List<MethodSpec> candidates = null;

			//
			// If S or T are nullable types, source_type and target_type are their underlying types
			// otherwise source_type and target_type are equal to S and T respectively.
			//
			TypeSpec source_type = source.Type;
			TypeSpec target_type = target;
			Expression source_type_expr;
			bool nullable_source = false;

			if (source_type.IsNullableType) {
				// No unwrapping conversion S? -> T for non-reference types
				if (implicitOnly && !TypeSpec.IsReferenceType (target_type) && !target_type.IsNullableType) {
					source_type_expr = source;
				} else {
					source_type_expr = Nullable.Unwrap.CreateUnwrapped (source);
					source_type = source_type_expr.Type;
					nullable_source = true;
				}
			} else {
				source_type_expr = source;
			}

			if (target_type.IsNullableType)
				target_type = Nullable.NullableInfo.GetUnderlyingType (target_type);

			// Only these containers can contain a user defined implicit or explicit operators
			const MemberKind user_conversion_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.TypeParameter;

			if ((source_type.Kind & user_conversion_kinds) != 0 && source_type.BuiltinType != BuiltinTypeSpec.Type.Decimal) {
				bool declared_only = source_type.IsStruct;

				var operators = MemberCache.GetUserOperator (source_type, Operator.OpType.Implicit, declared_only);
				if (operators != null) {
					FindApplicableUserDefinedConversionOperators (operators, source_type_expr, target_type, implicitOnly, ref candidates);
				}

				if (!implicitOnly) {
					operators = MemberCache.GetUserOperator (source_type, Operator.OpType.Explicit, declared_only);
					if (operators != null) {
						FindApplicableUserDefinedConversionOperators (operators, source_type_expr, target_type, false, ref candidates);
					}
				}
			}

			if ((target.Kind & user_conversion_kinds) != 0 && target_type.BuiltinType != BuiltinTypeSpec.Type.Decimal) {
				bool declared_only = target.IsStruct || implicitOnly;

				var operators = MemberCache.GetUserOperator (target_type, Operator.OpType.Implicit, declared_only);
				if (operators != null) {
					FindApplicableUserDefinedConversionOperators (operators, source_type_expr, target_type, implicitOnly, ref candidates);
				}

				if (!implicitOnly) {
					operators = MemberCache.GetUserOperator (target_type, Operator.OpType.Explicit, declared_only);
					if (operators != null) {
						FindApplicableUserDefinedConversionOperators (operators, source_type_expr, target_type, false, ref candidates);
					}
				}
			}

			if (candidates == null)
				return null;

			//
			// Find the most specific conversion operator
			//
			MethodSpec most_specific_operator;
			TypeSpec s_x, t_x;
			if (candidates.Count == 1) {
				most_specific_operator = candidates[0];
				s_x = most_specific_operator.Parameters.Types[0];
				t_x = most_specific_operator.ReturnType;
			} else {
				//
				// Pass original source type to find the best match against input type and
				// not the unwrapped expression
				//
				s_x = FindMostSpecificSource (candidates, source.Type, source_type_expr, !implicitOnly);
				if (s_x == null)
					return null;

				t_x = FindMostSpecificTarget (candidates, target, !implicitOnly);
				if (t_x == null)
					return null;

				most_specific_operator = null;
				for (int i = 0; i < candidates.Count; ++i) {
					if (candidates[i].ReturnType == t_x && candidates[i].Parameters.Types[0] == s_x) {
						most_specific_operator = candidates[i];
						break;
					}
				}

				if (most_specific_operator == null) {
					//
					// Unless running in probing more
					//
					if (!probingOnly) {
						MethodSpec ambig_arg = null;
						foreach (var candidate in candidates) {
							if (candidate.ReturnType == t_x)
								most_specific_operator = candidate;
							else if (candidate.Parameters.Types[0] == s_x)
								ambig_arg = candidate;
						}

						ec.Report.Error (457, loc,
							"Ambiguous user defined operators `{0}' and `{1}' when converting from `{2}' to `{3}'",
							ambig_arg.GetSignatureForError (), most_specific_operator.GetSignatureForError (),
							source.Type.GetSignatureForError (), target.GetSignatureForError ());
					}

					return ErrorExpression.Instance;
				}
			}

			//
			// Convert input type when it's different to best operator argument
			//
			if (s_x != source_type) {
				var c = source as Constant;
				if (c != null) {
					source = c.Reduce (ec, s_x);
					if (source == null)
						c = null;
				}

				if (c == null) {
					source = implicitOnly ?
						ImplicitConversionStandard (ec, source_type_expr, s_x, loc) :
						ExplicitConversionStandard (ec, source_type_expr, s_x, loc);
				}
			} else {
				source = source_type_expr;
			}

			source = new UserCast (most_specific_operator, source, loc).Resolve (ec);

			//
			// Convert result type when it's different to best operator return type
			//
			if (t_x != target_type) {
				//
				// User operator is of T?
				//
				if (t_x.IsNullableType && target.IsNullableType) {
					//
					// User operator return type does not match target type we need
					// yet another conversion. This should happen for promoted numeric
					// types only
					//
					if (t_x != target) {
						var unwrap = Nullable.Unwrap.CreateUnwrapped (source);

						source = implicitOnly ?
							ImplicitConversionStandard (ec, unwrap, target_type, loc) :
							ExplicitConversionStandard (ec, unwrap, target_type, loc);

						if (source == null)
							return null;

						source = new Nullable.LiftedConversion (source, unwrap, target).Resolve (ec);
					}
				} else {
					source = implicitOnly ?
						ImplicitConversionStandard (ec, source, target_type, loc) :
						ExplicitConversionStandard (ec, source, target_type, loc);

					if (source == null)
						return null;
				}
			}


			//
			// Source expression is of nullable type and underlying conversion returns
			// only non-nullable type we need to lift it manually
			//
			if (nullable_source && !s_x.IsNullableType)
				return new Nullable.LiftedConversion (source, source_type_expr, target).Resolve (ec);

			//
			// Target is of nullable type but source type is not, wrap the result expression
			//
			if (target.IsNullableType && !t_x.IsNullableType)
				source = Nullable.Wrap.Create (source, target);

			return source;
		}

		/// <summary>
		///   Converts implicitly the resolved expression `expr' into the
		///   `target_type'.  It returns a new expression that can be used
		///   in a context that expects a `target_type'.
		/// </summary>
		static public Expression ImplicitConversion (ResolveContext ec, Expression expr,
							     TypeSpec target_type, Location loc)
		{
			Expression e;

			if (target_type == null)
				throw new Exception ("Target type is null");

			e = ImplicitConversionStandard (ec, expr, target_type, loc);
			if (e != null)
				return e;

			e = ImplicitUserConversion (ec, expr, target_type, loc);
			if (e != null)
				return e;

			return null;
		}


		/// <summary>
		///   Attempts to apply the `Standard Implicit
		///   Conversion' rules to the expression `expr' into
		///   the `target_type'.  It returns a new expression
		///   that can be used in a context that expects a
		///   `target_type'.
		///
		///   This is different from `ImplicitConversion' in that the
		///   user defined implicit conversions are excluded.
		/// </summary>
		static public Expression ImplicitConversionStandard (ResolveContext ec, Expression expr,
								     TypeSpec target_type, Location loc)
		{
			return ImplicitConversionStandard (ec, expr, target_type, loc, false);
		}

		static Expression ImplicitConversionStandard (ResolveContext ec, Expression expr, TypeSpec target_type, Location loc, bool explicit_cast)
		{
			if (expr.eclass == ExprClass.MethodGroup){
				if (!target_type.IsDelegate){
					return null;
				}

				//
				// Only allow anonymous method conversions on post ISO_1
				//
				if (ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1){
					MethodGroupExpr mg = expr as MethodGroupExpr;
					if (mg != null)
						return new ImplicitDelegateCreation (target_type, mg, loc).Resolve (ec);
				}
			}

			TypeSpec expr_type = expr.Type;
			Expression e;

			if (expr_type == target_type) {
				if (expr_type != InternalType.NullLiteral && expr_type != InternalType.AnonymousMethod)
					return expr;
				return null;
			}

			if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
				switch (target_type.Kind) {
				case MemberKind.ArrayType:
				case MemberKind.Class:
					if (target_type.BuiltinType == BuiltinTypeSpec.Type.Object)
						return EmptyCast.Create (expr, target_type);

					goto case MemberKind.Struct;
				case MemberKind.Struct:
				case MemberKind.Delegate:
				case MemberKind.Enum:
				case MemberKind.Interface:
				case MemberKind.TypeParameter:
					Arguments args = new Arguments (1);
					args.Add (new Argument (expr));
					return new DynamicConversion (target_type, explicit_cast ? CSharpBinderFlags.ConvertExplicit : 0, args, loc).Resolve (ec);
				}

				return null;
			}

			if (target_type.IsNullableType)
				return ImplicitNulableConversion (ec, expr, target_type);

			//
			// Attempt to do the implicit constant expression conversions
			//
			Constant c = expr as Constant;
			if (c != null) {
				try {
					c = c.ConvertImplicitly (target_type);
				} catch {
					throw new InternalErrorException ("Conversion error", loc);
				}
				if (c != null)
					return c;
			}

			e = ImplicitNumericConversion (expr, expr_type, target_type);
			if (e != null)
				return e;

			e = ImplicitReferenceConversion (expr, target_type, explicit_cast);
			if (e != null)
				return e;

			e = ImplicitBoxingConversion (expr, expr_type, target_type);
			if (e != null)
				return e;

			if (expr is IntegralConstant && target_type.IsEnum){
				var i = (IntegralConstant) expr;
				//
				// LAMESPEC: csc allows any constant like 0 values to be converted, including const float f = 0.0
				//
				// An implicit enumeration conversion permits the decimal-integer-literal 0
				// to be converted to any enum-type and to any nullable-type whose underlying
				// type is an enum-type
				//
				if (i.IsZeroInteger) {
					// Recreate 0 literal to remove any collected conversions
					return new EnumConstant (new IntLiteral (ec.BuiltinTypes, 0, i.Location), target_type);
				}
			}

			if (ec.IsUnsafe) {
				var target_pc = target_type as PointerContainer;
				if (target_pc != null) {
					if (expr_type.IsPointer) {
						//
						// Pointer types are same when they have same element types
						//
						if (expr_type == target_pc)
							return expr;

						if (target_pc.Element.Kind == MemberKind.Void)
							return EmptyCast.Create (expr, target_type);

						//return null;
					}

					if (expr_type == InternalType.NullLiteral)
						return new NullPointer (target_type, loc);
				}
			}

			if (expr_type == InternalType.AnonymousMethod){
				AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
				Expression am = ame.Compatible (ec, target_type);
				if (am != null)
					return am.Resolve (ec);

				// Avoid CS1503 after CS1661
				return ErrorExpression.Instance;
			}

			if (expr_type == InternalType.Arglist && target_type == ec.Module.PredefinedTypes.ArgIterator.TypeSpec)
				return expr;

			//
			// dynamic erasure conversion on value types
			//
			if (expr_type.IsStruct && TypeSpecComparer.IsEqual (expr_type, target_type))
				return expr_type == target_type ? expr : EmptyCast.Create (expr, target_type);

			return null;
		}

		/// <summary>
		///   Attempts to implicitly convert `source' into `target_type', using
		///   ImplicitConversion.  If there is no implicit conversion, then
		///   an error is signaled
		/// </summary>
		static public Expression ImplicitConversionRequired (ResolveContext ec, Expression source,
								     TypeSpec target_type, Location loc)
		{
			Expression e = ImplicitConversion (ec, source, target_type, loc);
			if (e != null)
				return e;

			source.Error_ValueCannotBeConverted (ec, target_type, false);
			return null;
		}

		/// <summary>
		///   Performs the explicit numeric conversions
		///
		/// There are a few conversions that are not part of the C# standard,
		/// they were interim hacks in the C# compiler that were supposed to
		/// become explicit operators in the UIntPtr class and IntPtr class,
		/// but for historical reasons it did not happen, so the C# compiler
		/// ended up with these special hacks.
		///
		/// See bug 59800 for details.
		///
		/// The conversion are:
		///   UIntPtr->SByte
		///   UIntPtr->Int16
		///   UIntPtr->Int32
		///   IntPtr->UInt64
		///   UInt64->IntPtr
		///   SByte->UIntPtr
		///   Int16->UIntPtr
		///
		/// </summary>
		public static Expression ExplicitNumericConversion (ResolveContext rc, Expression expr, TypeSpec target_type)
		{
			// Not all predefined explicit numeric conversion are
			// defined here, for some of them (mostly IntPtr/UIntPtr) we
			// defer to user-operator handling which is now perfect but
			// works for now
			//
			// LAMESPEC: Undocumented IntPtr/UIntPtr conversions
			// IntPtr -> uint uses int
			// UIntPtr -> long uses ulong
			//

			switch (expr.Type.BuiltinType) {
			case BuiltinTypeSpec.Type.SByte:
				//
				// From sbyte to byte, ushort, uint, ulong, char, uintptr
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.I1_U1);
				case BuiltinTypeSpec.Type.UShort:
					return new ConvCast (expr, target_type, ConvCast.Mode.I1_U2);
				case BuiltinTypeSpec.Type.UInt:
					return new ConvCast (expr, target_type, ConvCast.Mode.I1_U4);
				case BuiltinTypeSpec.Type.ULong:
					return new ConvCast (expr, target_type, ConvCast.Mode.I1_U8);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.I1_CH);

				// One of the built-in conversions that belonged in the class library
				case BuiltinTypeSpec.Type.UIntPtr:
					return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I1_U8), target_type, target_type, true);
				}
				break;
			case BuiltinTypeSpec.Type.Byte:
				//
				// From byte to sbyte and char
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.U1_I1);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.U1_CH);
				}
				break;
			case BuiltinTypeSpec.Type.Short:
				//
				// From short to sbyte, byte, ushort, uint, ulong, char, uintptr
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.I2_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.I2_U1);
				case BuiltinTypeSpec.Type.UShort:
					return new ConvCast (expr, target_type, ConvCast.Mode.I2_U2);
				case BuiltinTypeSpec.Type.UInt:
					return new ConvCast (expr, target_type, ConvCast.Mode.I2_U4);
				case BuiltinTypeSpec.Type.ULong:
					return new ConvCast (expr, target_type, ConvCast.Mode.I2_U8);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.I2_CH);

				// One of the built-in conversions that belonged in the class library
				case BuiltinTypeSpec.Type.UIntPtr:
					return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I2_U8), target_type, target_type, true);
				}
				break;
			case BuiltinTypeSpec.Type.UShort:
				//
				// From ushort to sbyte, byte, short, char
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.U2_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.U2_U1);
				case BuiltinTypeSpec.Type.Short:
					return new ConvCast (expr, target_type, ConvCast.Mode.U2_I2);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.U2_CH);
				}
				break;
			case BuiltinTypeSpec.Type.Int:
				//
				// From int to sbyte, byte, short, ushort, uint, ulong, char, uintptr
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.I4_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.I4_U1);
				case BuiltinTypeSpec.Type.Short:
					return new ConvCast (expr, target_type, ConvCast.Mode.I4_I2);
				case BuiltinTypeSpec.Type.UShort:
					return new ConvCast (expr, target_type, ConvCast.Mode.I4_U2);
				case BuiltinTypeSpec.Type.UInt:
					return new ConvCast (expr, target_type, ConvCast.Mode.I4_U4);
				case BuiltinTypeSpec.Type.ULong:
					return new ConvCast (expr, target_type, ConvCast.Mode.I4_U8);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.I4_CH);

				// One of the built-in conversions that belonged in the class library
				case BuiltinTypeSpec.Type.UIntPtr:
					return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I2_U8), target_type, target_type, true);
				}
				break;
			case BuiltinTypeSpec.Type.UInt:
				//
				// From uint to sbyte, byte, short, ushort, int, char
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.U4_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.U4_U1);
				case BuiltinTypeSpec.Type.Short:
					return new ConvCast (expr, target_type, ConvCast.Mode.U4_I2);
				case BuiltinTypeSpec.Type.UShort:
					return new ConvCast (expr, target_type, ConvCast.Mode.U4_U2);
				case BuiltinTypeSpec.Type.Int:
					return new ConvCast (expr, target_type, ConvCast.Mode.U4_I4);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.U4_CH);
				}
				break;
			case BuiltinTypeSpec.Type.Long:
				//
				// From long to sbyte, byte, short, ushort, int, uint, ulong, char
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.I8_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.I8_U1);
				case BuiltinTypeSpec.Type.Short:
					return new ConvCast (expr, target_type, ConvCast.Mode.I8_I2);
				case BuiltinTypeSpec.Type.UShort:
					return new ConvCast (expr, target_type, ConvCast.Mode.I8_U2);
				case BuiltinTypeSpec.Type.Int:
					return new ConvCast (expr, target_type, ConvCast.Mode.I8_I4);
				case BuiltinTypeSpec.Type.UInt:
					return new ConvCast (expr, target_type, ConvCast.Mode.I8_U4);
				case BuiltinTypeSpec.Type.ULong:
					return new ConvCast (expr, target_type, ConvCast.Mode.I8_U8);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.I8_CH);
				}
				break;
			case BuiltinTypeSpec.Type.ULong:
				//
				// From ulong to sbyte, byte, short, ushort, int, uint, long, char
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.U8_U1);
				case BuiltinTypeSpec.Type.Short:
					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I2);
				case BuiltinTypeSpec.Type.UShort:
					return new ConvCast (expr, target_type, ConvCast.Mode.U8_U2);
				case BuiltinTypeSpec.Type.Int:
					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I4);
				case BuiltinTypeSpec.Type.UInt:
					return new ConvCast (expr, target_type, ConvCast.Mode.U8_U4);
				case BuiltinTypeSpec.Type.Long:
					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I8);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.U8_CH);

				// One of the built-in conversions that belonged in the class library
				case BuiltinTypeSpec.Type.IntPtr:
					return new OperatorCast (EmptyCast.Create (expr, rc.BuiltinTypes.Long), target_type, true);
				}
				break;
			case BuiltinTypeSpec.Type.Char:
				//
				// From char to sbyte, byte, short
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.CH_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.CH_U1);
				case BuiltinTypeSpec.Type.Short:
					return new ConvCast (expr, target_type, ConvCast.Mode.CH_I2);
				}
				break;
			case BuiltinTypeSpec.Type.Float:
				//
				// From float to sbyte, byte, short,
				// ushort, int, uint, long, ulong, char
				// or decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.R4_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.R4_U1);
				case BuiltinTypeSpec.Type.Short:
					return new ConvCast (expr, target_type, ConvCast.Mode.R4_I2);
				case BuiltinTypeSpec.Type.UShort:
					return new ConvCast (expr, target_type, ConvCast.Mode.R4_U2);
				case BuiltinTypeSpec.Type.Int:
					return new ConvCast (expr, target_type, ConvCast.Mode.R4_I4);
				case BuiltinTypeSpec.Type.UInt:
					return new ConvCast (expr, target_type, ConvCast.Mode.R4_U4);
				case BuiltinTypeSpec.Type.Long:
					return new ConvCast (expr, target_type, ConvCast.Mode.R4_I8);
				case BuiltinTypeSpec.Type.ULong:
					return new ConvCast (expr, target_type, ConvCast.Mode.R4_U8);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.R4_CH);
				case BuiltinTypeSpec.Type.Decimal:
					return new OperatorCast (expr, target_type, true);
				}
				break;
			case BuiltinTypeSpec.Type.Double:
				//
				// From double to sbyte, byte, short,
				// ushort, int, uint, long, ulong,
				// char, float or decimal
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_U1);
				case BuiltinTypeSpec.Type.Short:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_I2);
				case BuiltinTypeSpec.Type.UShort:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_U2);
				case BuiltinTypeSpec.Type.Int:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_I4);
				case BuiltinTypeSpec.Type.UInt:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_U4);
				case BuiltinTypeSpec.Type.Long:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_I8);
				case BuiltinTypeSpec.Type.ULong:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_U8);
				case BuiltinTypeSpec.Type.Char:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_CH);
				case BuiltinTypeSpec.Type.Float:
					return new ConvCast (expr, target_type, ConvCast.Mode.R8_R4);
				case BuiltinTypeSpec.Type.Decimal:
					return new OperatorCast (expr, target_type, true);
				}
				break;
			case BuiltinTypeSpec.Type.UIntPtr:
				//
				// Various built-in conversions that belonged in the class library
				//
				// from uintptr to sbyte, short, int32
				//
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new ConvCast (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type, ConvCast.Mode.U4_I1);
				case BuiltinTypeSpec.Type.Short:
					return new ConvCast (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type, ConvCast.Mode.U4_I2);
				case BuiltinTypeSpec.Type.Int:
					return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type);
				case BuiltinTypeSpec.Type.UInt:
					return new OperatorCast (expr, expr.Type, target_type, true);
				case BuiltinTypeSpec.Type.Long:
					return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.ULong, true), target_type);
				}
				break;
			case BuiltinTypeSpec.Type.IntPtr:
				if (target_type.BuiltinType == BuiltinTypeSpec.Type.UInt)
					return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.Int, true), target_type);
				if (target_type.BuiltinType == BuiltinTypeSpec.Type.ULong)
					return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.Long, true), target_type);
				
				break;
			case BuiltinTypeSpec.Type.Decimal:
				// From decimal to sbyte, byte, short,
				// ushort, int, uint, long, ulong, char,
				// float, or double
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
				case BuiltinTypeSpec.Type.Byte:
				case BuiltinTypeSpec.Type.Short:
				case BuiltinTypeSpec.Type.UShort:
				case BuiltinTypeSpec.Type.Int:
				case BuiltinTypeSpec.Type.UInt:
				case BuiltinTypeSpec.Type.Long:
				case BuiltinTypeSpec.Type.ULong:
				case BuiltinTypeSpec.Type.Char:
				case BuiltinTypeSpec.Type.Float:
				case BuiltinTypeSpec.Type.Double:
					return new OperatorCast (expr, expr.Type, target_type, true);
				}

				break;
			}

			return null;
		}

		/// <summary>
		///  Returns whether an explicit reference conversion can be performed
		///  from source_type to target_type
		/// </summary>
		public static bool ExplicitReferenceConversionExists (TypeSpec source_type, TypeSpec target_type)
		{
			Expression e = ExplicitReferenceConversion (null, source_type, target_type);
			if (e == null)
				return false;

			if (e == EmptyExpression.Null)
				return true;

			throw new InternalErrorException ("Invalid probing conversion result");
		}

		/// <summary>
		///   Implements Explicit Reference conversions
		/// </summary>
		static Expression ExplicitReferenceConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
		{
			//
			// From object to a generic parameter
			//
			if (source_type.BuiltinType == BuiltinTypeSpec.Type.Object && TypeManager.IsGenericParameter (target_type))
				return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);

			//
			// Explicit type parameter conversion.
			//
			if (source_type.Kind == MemberKind.TypeParameter)
				return ExplicitTypeParameterConversion (source, source_type, target_type);

			bool target_is_value_type = target_type.Kind == MemberKind.Struct || target_type.Kind == MemberKind.Enum;

			//
			// Unboxing conversion from System.ValueType to any non-nullable-value-type
			//
			if (source_type.BuiltinType == BuiltinTypeSpec.Type.ValueType && target_is_value_type)
				return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);

			//
			// From object or dynamic to any reference type or value type (unboxing)
			//
			if (source_type.BuiltinType == BuiltinTypeSpec.Type.Object || source_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
				if (target_type.IsPointer)
					return null;

				return
					source == null ? EmptyExpression.Null :
					target_is_value_type ? new UnboxCast (source, target_type) :
					source is Constant ? (Expression) new EmptyConstantCast ((Constant) source, target_type) :
					new ClassCast (source, target_type);
			}

			//
			// From any class S to any class-type T, provided S is a base class of T
			//
			if (source_type.Kind == MemberKind.Class && TypeSpec.IsBaseClass (target_type, source_type, true))
				return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);

			//
			// From any interface-type S to to any class type T, provided T is not
			// sealed, or provided T implements S.
			//
			if (source_type.Kind == MemberKind.Interface) {
				if (!target_type.IsSealed || target_type.ImplementsInterface (source_type, true)) {
					if (source == null)
						return EmptyExpression.Null;

					//
					// Unboxing conversion from any interface-type to any non-nullable-value-type that
					// implements the interface-type
					//
					return target_is_value_type ? new UnboxCast (source, target_type) : (Expression) new ClassCast (source, target_type);
				}

				//
				// From System.Collections.Generic.IList<T> and its base interfaces to a one-dimensional
				// array type S[], provided there is an implicit or explicit reference conversion from S to T.
				//
				var target_array = target_type as ArrayContainer;
				if (target_array != null && IList_To_Array (source_type, target_array))
					return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);

				return null;
			}

			var source_array = source_type as ArrayContainer;
			if (source_array != null) {
				var target_array = target_type as ArrayContainer;
				if (target_array != null) {
					//
					// From System.Array to any array-type
					//
					if (source_type.BuiltinType == BuiltinTypeSpec.Type.Array)
						return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);

					//
					// From an array type S with an element type Se to an array type T with an
					// element type Te provided all the following are true:
					//     * S and T differe only in element type, in other words, S and T
					//       have the same number of dimensions.
					//     * Both Se and Te are reference types
					//     * An explicit reference conversions exist from Se to Te
					//
					if (source_array.Rank == target_array.Rank) {

						source_type = source_array.Element;
						if (!TypeSpec.IsReferenceType (source_type))
							return null;

						var target_element = target_array.Element;
						if (!TypeSpec.IsReferenceType (target_element))
							return null;

						if (ExplicitReferenceConversionExists (source_type, target_element))
							return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
							
						return null;
					}
				}

				//
				// From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces, 
				// provided that there is an explicit reference conversion from S to T
				//
				if (ArrayToIList (source_array, target_type, true))
					return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);

				return null;
			}

			//
			// From any class type S to any interface T, provides S is not sealed
			// and provided S does not implement T.
			//
			if (target_type.IsInterface && !source_type.IsSealed && !source_type.ImplementsInterface (target_type, true)) {
				return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
			}

			//
			// From System delegate to any delegate-type
			//
			if (source_type.BuiltinType == BuiltinTypeSpec.Type.Delegate && target_type.IsDelegate)
				return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);

			//
			// From variant generic delegate to same variant generic delegate type
			//
			if (source_type.IsDelegate && target_type.IsDelegate && source_type.MemberDefinition == target_type.MemberDefinition) {
				var tparams = source_type.MemberDefinition.TypeParameters;
				var targs_src = source_type.TypeArguments;
				var targs_dst = target_type.TypeArguments;
				int i;
				for (i = 0; i < tparams.Length; ++i) {
					//
					// If TP is invariant, types have to be identical
					//
					if (TypeSpecComparer.IsEqual (targs_src[i], targs_dst[i]))
						continue;

					if (tparams[i].Variance == Variance.Covariant) {
						//
						//If TP is covariant, an implicit or explicit identity or reference conversion is required
						//
						if (ImplicitReferenceConversionExists (targs_src[i], targs_dst[i]))
							continue;

						if (ExplicitReferenceConversionExists (targs_src[i], targs_dst[i]))
							continue;

					} else if (tparams[i].Variance == Variance.Contravariant) {
						//
						//If TP is contravariant, both are either identical or reference types
						//
						if (TypeSpec.IsReferenceType (targs_src[i]) && TypeSpec.IsReferenceType (targs_dst[i]))
							continue;
					}

					break;
				}

				if (i == tparams.Length)
					return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
			}

			return null;
		}

		/// <summary>
		///   Performs an explicit conversion of the expression `expr' whose
		///   type is expr.Type to `target_type'.
		/// </summary>
		static public Expression ExplicitConversionCore (ResolveContext ec, Expression expr,
								 TypeSpec target_type, Location loc)
		{
			TypeSpec expr_type = expr.Type;

			// Explicit conversion includes implicit conversion and it used for enum underlying types too
			Expression ne = ImplicitConversionStandard (ec, expr, target_type, loc, true);
			if (ne != null)
				return ne;

			if (expr_type.IsEnum) {
				TypeSpec real_target = target_type.IsEnum ? EnumSpec.GetUnderlyingType (target_type) : target_type;
				Expression underlying = EmptyCast.Create (expr, EnumSpec.GetUnderlyingType (expr_type));
				if (underlying.Type == real_target)
					ne = underlying;

				if (ne == null)
					ne = ImplicitNumericConversion (underlying, real_target);

				if (ne == null)
					ne = ExplicitNumericConversion (ec, underlying, real_target);

				//
				// LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
				//
				if (ne == null && (real_target.BuiltinType == BuiltinTypeSpec.Type.IntPtr || real_target.BuiltinType == BuiltinTypeSpec.Type.UIntPtr))
					ne = ExplicitUserConversion (ec, underlying, real_target, loc);

				return ne != null ? EmptyCast.Create (ne, target_type) : null;
			}

			if (target_type.IsEnum) {
				//
				// System.Enum can be unboxed to any enum-type
				//
				if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Enum)
					return new UnboxCast (expr, target_type);

				TypeSpec real_target = target_type.IsEnum ? EnumSpec.GetUnderlyingType (target_type) : target_type;

				if (expr_type == real_target)
					return EmptyCast.Create (expr, target_type);

				Constant c = expr as Constant;
				if (c != null) {
					c = c.TryReduce (ec, real_target);
					if (c != null)
						return c;
				} else {
					ne = ImplicitNumericConversion (expr, real_target);
					if (ne != null)
						return EmptyCast.Create (ne, target_type);

					ne = ExplicitNumericConversion (ec, expr, real_target);
					if (ne != null)
						return EmptyCast.Create (ne, target_type);

					//
					// LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
					//
					if (expr_type.BuiltinType == BuiltinTypeSpec.Type.IntPtr || expr_type.BuiltinType == BuiltinTypeSpec.Type.UIntPtr) {
						ne = ExplicitUserConversion (ec, expr, real_target, loc);
						if (ne != null)
							return ExplicitConversionCore (ec, ne, target_type, loc);
					}
				}
			} else {
				ne = ExplicitNumericConversion (ec, expr, target_type);
				if (ne != null)
					return ne;
			}

			//
			// Skip the ExplicitReferenceConversion because we can not convert
			// from Null to a ValueType, and ExplicitReference wont check against
			// null literal explicitly
			//
			if (expr_type != InternalType.NullLiteral) {
				ne = ExplicitReferenceConversion (expr, expr_type, target_type);
				if (ne != null)
					return ne;
			}

			if (ec.IsUnsafe){
				ne = ExplicitUnsafe (expr, target_type);
				if (ne != null)
					return ne;
			}
			
			return null;
		}

		public static Expression ExplicitUnsafe (Expression expr, TypeSpec target_type)
		{
			TypeSpec expr_type = expr.Type;

			if (target_type.IsPointer){
				if (expr_type.IsPointer)
					return EmptyCast.Create (expr, target_type);

				switch (expr_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
				case BuiltinTypeSpec.Type.Short:
				case BuiltinTypeSpec.Type.Int:
					return new OpcodeCast (expr, target_type, OpCodes.Conv_I);

				case BuiltinTypeSpec.Type.UShort:
				case BuiltinTypeSpec.Type.UInt:
				case BuiltinTypeSpec.Type.Byte:
					return new OpcodeCast (expr, target_type, OpCodes.Conv_U);

				case BuiltinTypeSpec.Type.Long:
					return new ConvCast (expr, target_type, ConvCast.Mode.I8_I);

				case BuiltinTypeSpec.Type.ULong:
					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I);
				}
			}

			if (expr_type.IsPointer){
				switch (target_type.BuiltinType) {
				case BuiltinTypeSpec.Type.SByte:
					return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
				case BuiltinTypeSpec.Type.Byte:
					return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
				case BuiltinTypeSpec.Type.Short:
					return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
				case BuiltinTypeSpec.Type.UShort:
					return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
				case BuiltinTypeSpec.Type.Int:
					return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
				case BuiltinTypeSpec.Type.UInt:
					return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
				case BuiltinTypeSpec.Type.Long:
					return new ConvCast (expr, target_type, ConvCast.Mode.I_I8);
				case BuiltinTypeSpec.Type.ULong:
					return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
				}
			}
			return null;
		}

		/// <summary>
		///   Same as ExplicitConversion, only it doesn't include user defined conversions
		/// </summary>
		static public Expression ExplicitConversionStandard (ResolveContext ec, Expression expr,
								     TypeSpec target_type, Location l)
		{
			int errors = ec.Report.Errors;
			Expression ne = ImplicitConversionStandard (ec, expr, target_type, l);
			if (ec.Report.Errors > errors)
				return null;

			if (ne != null)
				return ne;

			ne = ExplicitNumericConversion (ec, expr, target_type);
			if (ne != null)
				return ne;

			ne = ExplicitReferenceConversion (expr, expr.Type, target_type);
			if (ne != null)
				return ne;

			if (ec.IsUnsafe && expr.Type.IsPointer && target_type.IsPointer && ((PointerContainer)expr.Type).Element.Kind == MemberKind.Void)
				return EmptyCast.Create (expr, target_type);

			expr.Error_ValueCannotBeConverted (ec, target_type, true);
			return null;
		}

		/// <summary>
		///   Performs an explicit conversion of the expression `expr' whose
		///   type is expr.Type to `target_type'.
		/// </summary>
		static public Expression ExplicitConversion (ResolveContext ec, Expression expr,
			TypeSpec target_type, Location loc)
		{
			Expression e = ExplicitConversionCore (ec, expr, target_type, loc);
			if (e != null) {
				//
				// Don't eliminate explicit precission casts
				//
				if (e == expr) {
					if (target_type.BuiltinType == BuiltinTypeSpec.Type.Float)
						return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
					
					if (target_type.BuiltinType == BuiltinTypeSpec.Type.Double)
						return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
				}
					
				return e;
			}

			TypeSpec expr_type = expr.Type;
			if (target_type.IsNullableType) {
				TypeSpec target;

				if (expr_type.IsNullableType) {
					target = Nullable.NullableInfo.GetUnderlyingType (target_type);
					Expression unwrap = Nullable.Unwrap.Create (expr);
					e = ExplicitConversion (ec, unwrap, target, expr.Location);
					if (e == null)
						return null;

					return new Nullable.LiftedConversion (e, unwrap, target_type).Resolve (ec);
				}
				if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Object) {
					return new UnboxCast (expr, target_type);
				}

				target = TypeManager.GetTypeArguments (target_type) [0];
				e = ExplicitConversionCore (ec, expr, target, loc);
				if (e != null)
					return TypeSpec.IsReferenceType (expr.Type) ? new UnboxCast (expr, target_type) : Nullable.Wrap.Create (e, target_type);
			} else if (expr_type.IsNullableType) {
				e = ImplicitBoxingConversion (expr, Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type);
				if (e != null)
					return e;

				e = Nullable.Unwrap.Create (expr, false);			
				e = ExplicitConversionCore (ec, e, target_type, loc);
				if (e != null)
					return EmptyCast.Create (e, target_type);
			}
			
			e = ExplicitUserConversion (ec, expr, target_type, loc);
			if (e != null)
				return e;			

			expr.Error_ValueCannotBeConverted (ec, target_type, true);
			return null;
		}
	}
}